i have problem writing java code to remove repeated letters from word.This code will remove repeated letter by accepting only one of the letter which is repeating . Suppose, if input is "SUSHIL" then output would be "SUHIL".
This java code i write.
import java.io.*;
import java.util.*;
public class Repeat
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
char ch1, ch2;
int i, j;
int l = name.length();
String result = "";
for (i = 0; i < l; i++)
{
for (j = 1; j < l; j++)
{
ch1 = name.charAt(i);
ch2 = name.charAt(j);
if (ch1 != ch2)
{
result = result + ch1;
break;
}
}
}
System.out.println("Output:" + result);
}
}
try this:
private static String removeRepeat(String input){
Set<Character> str = new LinkedHashSet<Character>();
for(int n=0;n<input.length();n++){
str.add(input.charAt(n));
}
return str.toString();
}
good point from the comment, changed to LinkedHashSet.
It may be the crap code, but what I mean is don't reinvent the wheel, only if you have to
char ch1,ch2;
int l=name.length();
String result="";
for(int i=0;i<l;i++){
if(name.indexOf(name.charAt(i))==i){
result+=name.charAt(i);
}
}
System.out.println(result);
input = SUSHSILHI
output = SUHIL
You should do the opposite: add the first letter to result, then check if the next letter is already in result:
boolean exist=false;
result=name.charAt(0);
for (i=1; i<l;i++) {
exist=false;
int j=0;
while (exist=false && j<i) {
if(name.charAt(i)==charAt(j)) {
exist=true;
}
j++;
}
if(exist==false){
result=result+name.charAt(i);
}
}
The for checks for all the string name, then the while checks for the characters already in result, if it doesn't already exist, else it doesn't do anything.
Using indexOf() , one for loop should work, like below
String name="SUSHIL";
String newName="";
int i=0;
int l=name.length();
for(i=0;i<l;i++)
{
char ch1=name.charAt(i);
if(!(newName.indexOf(ch1)>-1))
{
newName=newName + ch1;
}
}
System.out.println("Output:"+newName);
String name = "SUSHIL";
char ch1 = 0, ch2;
int i, j;
int l = name.length();
StringBuilder sb = new StringBuilder();
for (i = 0; i < l; i++)
{
//this is used to append char to StringBuilder
boolean shouldAppend = true;
//if we don't check if the length is equal to 0 to start then the below loop will never run and the result would be an empty string so just append the first character to the StringBuilder
if (sb.length() == 0)
{
sb.append(name.charAt(i));
shouldAppend = false;
}
else
{
for (j = 0; j < sb.length(); j++)
{
ch1 = name.charAt(i);
ch2 = sb.charAt(j);
if (ch1 == ch2)
{
//StringBuilder contains ch1 so turn shouldAppend to false and break out of this inner loop
shouldAppend = false;
break;
}
}
}
if (shouldAppend) sb.append(ch1);
}
System.out.println("Output:" + sb.toString());
Try:
//Globally
List<Character> list = new ArrayList<Character>();
public String remRepeats(String original)
{
char ch = original.charAt(0);
if (original.length() == 1)
return original;
if (list.contains(ch))
return remRepeats(original.substring(1));
else
{
list.add(ch);
return ch + remRepeats(original.substring(1));
}
}
List<Character> characters = new ArrayList<>();
char[] chars = name.toCharArray();
StringBuilder stringBuilder = new StringBuilder();
for(char currChar:chars) {
if (!characters.contains(currChar)) {
characters.add(currChar);
stringBuilder.append(currChar);
}
}
System.out.println(stringBuilder);
Related
public static void reverse() {
int x=0;
char temp = 0;
String toStrore;
char checkSpace=' ';
System.out.println("Enter a line to reverse");
Scanner sc=new Scanner(System.in);
String userInput=sc.nextLine();
char[] charArray=userInput.toCharArray();
for(int i=charArray.length-1;i>=0;i--){
char tchar=charArray[i];
while(tchar==checkSpace){
x = ++i;
for(int j=x;j<=charArray.length-1;i++){
temp=(char) (temp+charArray[j]);
System.out.print(temp);
}
}
}
}
Please help me with logic.
NOTE: I DONT WANT TO USE ANY INBUILT FUNCTION EXCEPT lenght().
Here something, but you have to at least use String.charAt() and String.length(). The string is reversed by searching backwards until you find a space. Then it appends what's after the space until it reaches the end of the string or finds another space. Lastly, the first word will get added to the result.
public class MyClass {
public static void main(String args[]) {
System.out.println(reverse("The quick brown fox jumps over the lazy dog"));
}
private static String reverse(String data) {
String result = "";
// Build the string in reverse as you find spaces
for (int i = data.length() - 1; i > -1; i--) {
if (data.charAt(i) == ' ') {
int j = i + 1;
while (j < data.length() && data.charAt(j) != ' ') {
result += data.charAt(j++);
}
result += " ";
}
}
// Add the first word to the result
int i = 0;
while (i < data.length() && data.charAt(i) != ' ') {
result += data.charAt(i++);
}
return result;
}
}
Result
dog lazy the over jumps fox brown quick The
try out this one
import java.util.Arrays;
public class Reverse {
public static void main(String... args) {
getReversed("Tom Cat");
}
public static void getReversed(String str) {
char[] arr = str.toCharArray();
int len = 0;
for (char ch : arr) {
if (ch == ' ') {
len++;
}
}
String[] res = new String[len + 1];
int start = 0;
int idx = len;
while (idx > -1) {
StringBuilder builder = new StringBuilder();
for (int i = start; i < arr.length; i++) {
if (arr[i] != ' ') {
builder.append(arr[i]);
if (i == arr.length - 1) {
res[idx--] = builder.toString();
}
} else {
res[idx--] = builder.toString();
builder.setLength(0);
start = i;
}
}
}
System.out.println(Arrays.toString(res));
}
}
Updated optimized code
public static void main(String... args) {
String str = "Cat Tom";
char[] charArr = str.toCharArray();
int len = charArr.length;
ArrayList<String> list = new ArrayList<>();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < len; i++) {
char ch = charArr[i];
if (ch == ' ') {
list.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
} else if (i == len - 1) {
list.add(stringBuilder.append(ch).toString());
} else {
stringBuilder.append(ch);
}
}
Collections.reverse(list);
System.out.println(list);
}
Output
[Cat, Tom]
I have this code that is supposed to do what the title said, reverse the order of characters without changing the order of the words:
package stackTests;
import java.util.Scanner;
import java.util.Stack;
public class StackTest
{
Stack<Character> stack;
public StackTest()
{
stack = new Stack<Character>();
}
public String reverseString(String str)
{
int start = 0;
int start2 = 0;
int size;
char space = ' ';
char[] cArr;
Scanner scan = new Scanner(str);
cArr = str.toCharArray();
for (; start < cArr.length; start++)
{
if(cArr[start] == space || start == cArr.length - 1)
{
for (; start2 < stack.size(); start++)
{
System.out.print(stack.pop());
}
}
else
{
stack.push(cArr[start]);
}
start2 = 0;
}
return str;
}
}
It works fine if I enter a single word like "Hello"--it will output "olleH"--but as soon as it gets more complicated than one word it starts to output some weird things."Hello my name is" outputs "ollehem". I'm really new to Stacks and this is my first time using them. I'm not sure if there is a logic error or improper use of Stacks.
you're not outputting original spaces, this is why you're seeing strange results
here is fixed version:
public static void reverseString(final String str) {
final Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
final char c = str.charAt(i);
if (c == ' ') {
while (!stack.isEmpty())
System.out.print(stack.pop());
System.out.print(' ');
} else
stack.push(c);
}
while (!stack.isEmpty())
System.out.print(stack.pop());
}
another version without stack, with in-place replacement:
public static void reverseString(final String str) {
final char[] chars = str.toCharArray();
int start = 0;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == ' ') {
reverse(chars, start, i - 1);
start = i + 1;
}
}
reverse(chars, start, chars.length - 1);
System.out.println(new String(chars));
}
private static void reverse(final char[] chars, int s, int e) {
while (s < e) {
final char t = chars[s];
chars[s] = chars[e];
chars[e] = t;
s++;
e--;
}
}
If you HAVE to use a stack, I would follow an algorithm like this:
String myString = "Hello World";
Stack<Character> stack = new Stack<Character>();
StringBuilder sb = new StringBuilder();
String[] splitString = myString.split(" ");
//Iterate through each word in the string
for(String s : splitString){
//Push each character of the word into LIFO stack
for(char c : s.toCharArray()){
stack.push(c);
}
//Build new string with reverse ordered characters
while(!stack.isEmpty()){
sb.append(stack.pop());
}
//Append a space as long as it's not the last word of the original string
if(!s.equals(splitString[splitString.length - 1]))
sb.append(" ");
}
//Print the new string
System.out.println(sb.toString());
I'm not sure efficiency matters to you, but this algorithm would work in linear time, where n is the number of characters in the string.
Here is how you can do it in-place without using any extra space (Not using stack):
public class ReverseWordsInplace {
public static void main(String[] args) {
reverseWords(new StringBuilder("This is a test"));
}
public static void reverseWords(StringBuilder s) {
StringBuilder str = new StringBuilder(s);
int startWordIndex = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ' || str.length() - 1 == i) {
int x = 0;
int endWordIndex = str.charAt(i) == ' ' ? i - 1 : i;
while (endWordIndex - x > startWordIndex + x) {
char c1 = str.charAt(startWordIndex + x);
char c2 = str.charAt(endWordIndex - x);
str.setCharAt(startWordIndex + x, c2);
str.setCharAt(endWordIndex - x, c1);
x++;
}
startWordIndex = i + 1;
}
}
System.out.println(str);
}
}
Output:
sihT si a tset
I am new to java programming. I want to print a string with alternate characters in UpperCase.
String x=jTextField1.getText();
x=x.toLowerCase();
int y=x.length();
for(int i=1;i<=y;i++)
{}
I don't know how to proceed further. I want to do this question with the help of looping and continue function.
Help would be appreciated. Thanks.
#Test
public void alternateUppercase(){
String testString = "This is a !!!!! test - of the emergency? broadcast System.";
char[] arr = testString.toLowerCase().toCharArray();
boolean makeUppercase = true;
for (int i=0; i<arr.length; i++) {
if(makeUppercase && Character.isLetter(arr[i])) {
arr[i] = Character.toUpperCase(arr[i]);
makeUppercase = false;
} else if (!makeUppercase && Character.isLetter(arr[i])) {
makeUppercase = true;
}
}
String convertedString = String.valueOf(arr);
System.out.println(convertedString);
}
First, java indexes start at 0 (not 1). I think you are asking for something as simple as alternating calls to Character.toLowerCase(char) and Character.toUpperCase(char) on the result of modulo (remainder of division) 2.
String x = jTextField1.getText();
for (int i = 0, len = x.length(); i < len; i++) {
char ch = x.charAt(i);
if (i % 2 == 0) {
System.out.print(Character.toLowerCase(ch));
} else {
System.out.print(Character.toUpperCase(ch));
}
}
System.out.println();
Strings start at index 0 and finish at index x.length()-1
To look up a String by index you can use String.charAt(i)
To convert a character to upper case you can do Character.toUpperCase(ch);
I suggest you build a StringBuilder from these characters which you can toString() when you are done.
you can make it using the 65 distnace of lower case and upper case ABCabc from the unicode table like:
String str = "abbfFDdshFSDjdFDSsfsSdoi".toLowerCase();
char c;
boolean state = false;
String newStr = "";
for (int i=0; i<str.length(); i++){
c = str.charAt(o);
if (state){
newStr += c;
}
else {
newStr += c + 65;
}
state = !state;
}
I'm sure there is a slicker way to do this, but this will work for a 2 minute-answer:
public String homeWork(){
String x = "Hello World";
StringBuilder sb = new StringBuilder();
for(int i=0;i<=x.length();i++){
char c = x.charAt(i);
if(i%2==0){
sb.append(String.valueOf(c).toUpperCase());
} else {
sb.append(String.valueOf(c).toLowerCase());
}
}
return sb.toString();
}
To explain i%2==0, if the remainder of i divided by 2 is equal to zero (even numbered) return true
public class PrintingStringInAlternativeCase {
public static void main(String s[])
{
String testString = "TESTSTRING";
String output = "";
for (int i = 0; i < testString.length(); i++) {
if(i%2 == 0)
{
output += Character.toUpperCase(testString.toCharArray()[i]);
}else
{
output += Character.toLowerCase(testString.toCharArray()[i]);
}
}
System.out.println("Newly generated string is as follow: "+ output);
}
}
Using as much of your code as I could, here's what I got. First I made a string called build that will help you build your resulting string. Also, I changed the index to go from [0,size-1] not [1,size]. Using modulo devision of 2 helps with the "every other" bit.
String build =""
String x=jTextField1.getText();
x=x.toLowerCase();
int y=x.length();
for(int i=0;i<y;i++)
{
if(i%2==0){
build+=Character.toUpperCase(x.charAt(i));
else{
build+=x.charAt(i);
}
}
x=build; //not necessary, you could just use build.
Happy oding! Leave a comment if you have any questions.
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Stirng");
String str=sc.nextLine();
for(int i=0;i<str.length();i++)
{
if(i%2==0)
{
System.out.print(Character.toLowerCase(str.charAt(i)));
}
else
{
System.out.print(Character.toUpperCase(str.charAt(i)));
}
}
sc.close();
}
Java 8 Solution:
static String getMixedCase(String str) {
char[] chars = str.toCharArray();
return IntStream.range(0, str.length())
.mapToObj(i -> String.valueOf(i % 2 == 1 ? chars[i] : Character.toUpperCase(chars[i])))
.collect(Collectors.joining());
}
public class ClassC {
public static void main(String[] args) {
String str = "Hello";
StringBuffer strNew = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
if (i % 2 == 0) {
strNew.append(Character.toLowerCase(str.charAt(i)));
} else {
strNew.append(Character.toUpperCase(str.charAt(i)));
}
}
System.out.println(strNew);
}
}
I need to create a method that receives a String and also returns a String.
Ex input: AAABBBBCC
Ex output: 3A4B2C
Well, this is quite embarrassing and I couldn't manage to do it on the interview that I had today ( I was applying for a Junior position ), now, trying at home I made something that works statically, I mean, not using a loop which is kind of useless but I don't know if I'm not getting enough hours of sleep or something but I can't figure it out how my for loop should look like. This is the code:
public static String Comprimir(String texto){
StringBuilder objString = new StringBuilder();
int count;
char match;
count = texto.substring(texto.indexOf(texto.charAt(1)), texto.lastIndexOf(texto.charAt(1))).length()+1;
match = texto.charAt(1);
objString.append(count);
objString.append(match);
return objString.toString();
}
Thanks for your help, I'm trying to improve my logic skills.
Loop through the string remembering what you last saw. Every time you see the same letter count. When you see a new letter put what you have counted onto the output and set the new letter as what you have last seen.
String input = "AAABBBBCC";
int count = 1;
char last = input.charAt(0);
StringBuilder output = new StringBuilder();
for(int i = 1; i < input.length(); i++){
if(input.charAt(i) == last){
count++;
}else{
if(count > 1){
output.append(""+count+last);
}else{
output.append(last);
}
count = 1;
last = input.charAt(i);
}
}
if(count > 1){
output.append(""+count+last);
}else{
output.append(last);
}
System.out.println(output.toString());
You can do that using the following steps:
Create a HashMap
For every character, Get the value from the hashmap
-If the value is null, enter 1
-else, replace the value with (value+1)
Iterate over the HashMap and keep concatenating (Value+Key)
use StringBuilder (you did that)
define two variables - previousChar and counter
loop from 0 to str.length() - 1
each time get str.charat(i) and compare it to what's stored in the previousChar variable
if the previous char is the same, increment a counter
if the previous char is not the same, and counter is 1, increment counter
if the previous char is not the same, and counter is >1, append counter + currentChar, reset counter
after the comparison, assign the current char previousChar
cover corner cases like "first char"
Something like that.
The easiest approach:- Time Complexity - O(n)
public static void main(String[] args) {
String str = "AAABBBBCC"; //input String
int length = str.length(); //length of a String
//Created an object of a StringBuilder class
StringBuilder sb = new StringBuilder();
int count=1; //counter for counting number of occurances
for(int i=0; i<length; i++){
//if i reaches at the end then append all and break the loop
if(i==length-1){
sb.append(str.charAt(i)+""+count);
break;
}
//if two successive chars are equal then increase the counter
if(str.charAt(i)==str.charAt(i+1)){
count++;
}
else{
//else append character with its count
sb.append(str.charAt(i)+""+count);
count=1; //reseting the counter to 1
}
}
//String representation of a StringBuilder object
System.out.println(sb.toString());
}
In the count=... line, lastIndexOf will not care about consecutive values, and will just give the last occurence.
For instance, in the string "ABBA", the substring would be the whole string.
Also, taking the length of the substring is equivalent to subtracting the two indexes.
I really think that you need a loop.
Here is an example :
public static String compress(String text) {
String result = "";
int index = 0;
while (index < text.length()) {
char c = text.charAt(index);
int count = count(text, index);
if (count == 1)
result += "" + c;
else
result += "" + count + c;
index += count;
}
return result;
}
public static int count(String text, int index) {
char c = text.charAt(index);
int i = 1;
while (index + i < text.length() && text.charAt(index + i) == c)
i++;
return i;
}
public static void main(String[] args) {
String test = "AAABBCCC";
System.out.println(compress(test));
}
Please try this one. This may help to print the count of characters which we pass on string format through console.
import java.util.*;
public class CountCharacterArray {
private static Scanner inp;
public static void main(String args[]) {
inp = new Scanner(System.in);
String str=inp.nextLine();
List<Character> arrlist = new ArrayList<Character>();
for(int i=0; i<str.length();i++){
arrlist.add(str.charAt(i));
}
for(int i=0; i<str.length();i++){
int freq = Collections.frequency(arrlist, str.charAt(i));
System.out.println("Frequency of "+ str.charAt(i)+ " is: "+freq);
}
}
}
Java's not my main language, hardly ever use it, but I wanted to give it a shot :]
Not even sure if your assignment requires a loop, but here's a regexp approach:
public static String compress_string(String inp) {
String compressed = "";
Pattern pattern = Pattern.compile("([\\w])\\1*");
Matcher matcher = pattern.matcher(inp);
while(matcher.find()) {
String group = matcher.group();
if (group.length() > 1) compressed += group.length() + "";
compressed += group.charAt(0);
}
return compressed;
}
This is just one more way of doing it.
public static String compressor(String raw) {
StringBuilder builder = new StringBuilder();
int counter = 0;
int length = raw.length();
int j = 0;
while (counter < length) {
j = 0;
while (counter + j < length && raw.charAt(counter + j) == raw.charAt(counter)) {
j++;
}
if (j > 1) {
builder.append(j);
}
builder.append(raw.charAt(counter));
counter += j;
}
return builder.toString();
}
The following can be used if you are looking for a basic solution. Iterate through the string with one element and after finding all the element occurrences, remove that character. So that it will not interfere in the next search.
public static void main(String[] args) {
String string = "aaabbbbbaccc";
int counter;
String result="";
int i=0;
while (i<string.length()){
counter=1;
for (int j=i+1;j<string.length();j++){
System.out.println("string length ="+string.length());
if (string.charAt(i) == string.charAt(j)){
counter++;
}
}
result = result+string.charAt(i)+counter;
string = string.replaceAll(String.valueOf(string.charAt(i)), "");
}
System.out.println("result is = "+result);
}
And the output will be :=
result is = a4b5c3
private String Comprimir(String input){
String output="";
Map<Character,Integer> map=new HashMap<Character,Integer>();
for(int i=0;i<input.length();i++){
Character character=input.charAt(i);
if(map.containsKey(character)){
map.put(character, map.get(character)+1);
}else
map.put(character, 1);
}
for (Entry<Character, Integer> entry : map.entrySet()) {
output+=entry.getValue()+""+entry.getKey().charValue();
}
return output;
}
One other simple way using Multiset of guava-
import java.util.Arrays;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import com.google.common.collect.Multiset.Entry;
public class WordSpit {
public static void main(String[] args) {
String output="";
Multiset<String> wordsMultiset = HashMultiset.create();
String[] words="AAABBBBCC".split("");
wordsMultiset.addAll(Arrays.asList(words));
for (Entry<String> string : wordsMultiset.entrySet()) {
if(!string.getElement().isEmpty())
output+=string.getCount()+""+string.getElement();
}
System.out.println(output);
}
}
consider the below Solution in which the String s1 identifies the unique characters that are available in a given String s (for loop 1), in the second for loop build a string s2 that contains unique character and no of times it is repeated by comparing string s1 with s.
public static void main(String[] args)
{
// TODO Auto-generated method stub
String s = "aaaabbccccdddeee";//given string
String s1 = ""; // string to identify how many unique letters are available in a string
String s2=""; //decompressed string will be appended to this string
int count=0;
for(int i=0;i<s.length();i++) {
if(s1.indexOf(s.charAt(i))<0) {
s1 = s1+s.charAt(i);
}
}
for(int i=0;i<s1.length();i++) {
for(int j=0;j<s.length();j++) {
if(s1.charAt(i)==s.charAt(j)) {
count++;
}
}
s2=s2+s1.charAt(i)+count;
count=0;
}
System.out.println(s2);
}
It may help you.
public class StringCompresser
{
public static void main(String[] args)
{
System.out.println(compress("AAABBBBCC"));
System.out.println(compress("AAABC"));
System.out.println(compress("A"));
System.out.println(compress("ABBDCC"));
System.out.println(compress("AZXYC"));
}
static String compress(String str)
{
StringBuilder stringBuilder = new StringBuilder();
char[] charArray = str.toCharArray();
int count = 1;
char lastChar = 0;
char nextChar = 0;
lastChar = charArray[0];
for (int i = 1; i < charArray.length; i++)
{
nextChar = charArray[i];
if (lastChar == nextChar)
{
count++;
}
else
{
stringBuilder.append(count).append(lastChar);
count = 1;
lastChar = nextChar;
}
}
stringBuilder.append(count).append(lastChar);
String compressed = stringBuilder.toString();
return compressed;
}
}
Output:
3A4B2C
3A1B1C
1A
1A2B1D2C
1A1Z1X1Y1C
The answers which used Map will not work for cases like aabbbccddabc as in that case the output should be a2b3c2d2a1b1c1.
In that case this implementation can be used :
private String compressString(String input) {
String output = "";
char[] arr = input.toCharArray();
Map<Character, Integer> myMap = new LinkedHashMap<>();
for (int i = 0; i < arr.length; i++) {
if (i > 0 && arr[i] != arr[i - 1]) {
output = output + arr[i - 1] + myMap.get(arr[i - 1]);
myMap.put(arr[i - 1], 0);
}
if (myMap.containsKey(arr[i])) {
myMap.put(arr[i], myMap.get(arr[i]) + 1);
} else {
myMap.put(arr[i], 1);
}
}
for (Character c : myMap.keySet()) {
if (myMap.get(c) != 0) {
output = output + c + myMap.get(c);
}
}
return output;
}
O(n) approach
No need for hashing. The idea is to find the first Non-matching character.
The count of each character would be the difference in the indices of both characters.
for a detailed answer: https://stackoverflow.com/a/55898810/7972621
The only catch is that we need to add a dummy letter so that the comparison for
the last character is possible.
private static String compress(String s){
StringBuilder result = new StringBuilder();
int j = 0;
s = s + '#';
for(int i=1; i < s.length(); i++){
if(s.charAt(i) != s.charAt(j)){
result.append(i-j);
result.append(s.charAt(j));
j = i;
}
}
return result.toString();
}
The code below will ask the user for user to input a specific character to count the occurrence .
import java.util.Scanner;
class CountingOccurences {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
String str;
char ch;
int count=0;
System.out.println("Enter the string:");
str=inp.nextLine();
System.out.println("Enter th Char to see the occurence\n");
ch=inp.next().charAt(0);
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)==ch)
{
count++;
}
}
System.out.println("The Character is Occuring");
System.out.println(count+"Times");
}
}
public static char[] compressionTester( char[] s){
if(s == null){
throw new IllegalArgumentException();
}
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0 ; i < s.length ; i++) {
if(!map.containsKey(s[i])){
map.put(s[i], 1);
}
else{
int value = map.get(s[i]);
value++;
map.put(s[i],value);
}
}
String newer="";
for( Character n : map.keySet()){
newer = newer + n + map.get(n);
}
char[] n = newer.toCharArray();
if(s.length > n.length){
return n;
}
else{
return s;
}
}
package com.tell.datetime;
import java.util.Stack;
public class StringCompression {
public static void main(String[] args) {
String input = "abbcccdddd";
System.out.println(compressString(input));
}
public static String compressString(String input) {
if (input == null || input.length() == 0)
return input;
String finalCompressedString = "";
String lastElement="";
char[] charArray = input.toCharArray();
Stack stack = new Stack();
int elementCount = 0;
for (int i = 0; i < charArray.length; i++) {
char currentElement = charArray[i];
if (i == 0) {
stack.push((currentElement+""));
continue;
} else {
if ((currentElement+"").equalsIgnoreCase((String)stack.peek())) {
stack.push(currentElement + "");
if(i==charArray.length-1)
{
while (!stack.isEmpty()) {
lastElement = (String)stack.pop();
elementCount++;
}
finalCompressedString += lastElement + "" + elementCount;
}else
continue;
}
else {
while (!stack.isEmpty()) {
lastElement = (String)stack.pop();
elementCount++;
}
finalCompressedString += lastElement + "" + elementCount;
elementCount=0;
stack.push(currentElement+"");
}
}
}
if (finalCompressedString.length() >= input.length())
return input;
else
return finalCompressedString;
}
}
public class StringCompression {
public static void main(String[] args){
String s = "aabcccccaaazdaaa";
char check = s.charAt(0);
int count = 0;
for(int i=0; i<s.length(); i++){
if(s.charAt(i) == check) {
count++;
if(i==s.length()-1){
System.out.print(s.charAt(i));
System.out.print(count);
}
} else {
System.out.print(s.charAt(i-1));
System.out.print(count);
check = s.charAt(i);
count = 1;
if(i==s.length()-1){
System.out.print(s.charAt(i));
System.out.print(count);
}
}
}
}
// O(N) loop through entire character array
// match current char with next one, if they matches count++
// if don't then just append current char and counter value and then reset counter.
// special case is the last characters, for that just check if count value is > 0, if it's then append the counter value and the last char
private String compress(String str) {
char[] c = str.toCharArray();
String newStr = "";
int count = 1;
for (int i = 0; i < c.length - 1; i++) {
int j = i + 1;
if (c[i] == c[j]) {
count++;
} else {
newStr = newStr + c[i] + count;
count = 1;
}
}
// this is for the last strings...
if (count > 0) {
newStr = newStr + c[c.length - 1] + count;
}
return newStr;
}
public class StringCompression {
public static void main(String... args){
String s="aabbcccaa";
//a2b2c3a2
for(int i=0;i<s.length()-1;i++){
int count=1;
while(i<s.length()-1 && s.charAt(i)==s.charAt(i+1)){
count++;
i++;
}
System.out.print(s.charAt(i));
System.out.print(count);
}
System.out.println(" ");
}
}
This is a leet code problem 443. Most of the answers here uses StringBuilder or a HashMap, the actual problem statement is to solve using the input char array and in place array modification.
public int compress(char[] chars) {
int startIndex = 0;
int lastArrayIndex = 0;
if (chars.length == 1) {
return 1;
}
if (chars.length == 0) {
return 0;
}
for (int j = startIndex + 1; j < chars.length; j++) {
if (chars[startIndex] != chars[j]) {
chars[lastArrayIndex] = chars[startIndex];
lastArrayIndex++;
if ((j - startIndex) > 1) {
for (char c : String.valueOf(j - startIndex).toCharArray()) {
chars[lastArrayIndex] = c;
lastArrayIndex++;
}
}
startIndex = j;
}
if (j == chars.length - 1) {
if (j - startIndex >= 1) {
j = chars.length;
chars[lastArrayIndex] = chars[startIndex];
lastArrayIndex++;
for (char c : String.valueOf(j - startIndex).toCharArray()) {
chars[lastArrayIndex] = c;
lastArrayIndex++;
}
} else {
chars[lastArrayIndex] = chars[startIndex];
lastArrayIndex++;
}
}
}
return lastArrayIndex;
}
}
I was wondering how I would write a method to count the number of words in a java string only by using string methods like charAt, length, or substring.
Loops and if statements are okay!
I really appreciate any help I can get! Thanks!
This would work even with multiple spaces and leading and/or trailing spaces and blank lines:
String trim = s.trim();
if (trim.isEmpty())
return 0;
return trim.split("\\s+").length; // separate string around spaces
More info about split here.
public static int countWords(String s){
int wordCount = 0;
boolean word = false;
int endOfLine = s.length() - 1;
for (int i = 0; i < s.length(); i++) {
// if the char is a letter, word = true.
if (Character.isLetter(s.charAt(i)) && i != endOfLine) {
word = true;
// if char isn't a letter and there have been letters before,
// counter goes up.
} else if (!Character.isLetter(s.charAt(i)) && word) {
wordCount++;
word = false;
// last word of String; if it doesn't end with a non letter, it
// wouldn't count without this.
} else if (Character.isLetter(s.charAt(i)) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
Hi I just figured out with StringTokenizer like this:
String words = "word word2 word3 word4";
StringTokenizer st = new Tokenizer(words);
st.countTokens();
Simply use ,
str.split("\\w+").length ;
public static int countWords(String str){
if(str == null || str.isEmpty())
return 0;
int count = 0;
for(int e = 0; e < str.length(); e++){
if(str.charAt(e) != ' '){
count++;
while(str.charAt(e) != ' ' && e < str.length()-1){
e++;
}
}
}
return count;
}
private static int countWordsInSentence(String input) {
int wordCount = 0;
if (input.trim().equals("")) {
return wordCount;
}
else {
wordCount = 1;
}
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
String str = new String("" + ch);
if (i+1 != input.length() && str.equals(" ") && !(""+ input.charAt(i+1)).equals(" ")) {
wordCount++;
}
}
return wordCount;
}
Use
myString.split("\\s+");
This will work.
There is a Simple Solution You can Try this code
String s = "hju vg jhdgsf dh gg g g g ";
String[] words = s.trim().split("\\s+");
System.out.println("count is = "+(words.length));
public static int countWords(String input) {
int wordCount = 0;
boolean isBlankSet = false;
input = input.trim();
for (int j = 0; j < input.length(); j++) {
if (input.charAt(j) == ' ')
isBlankSet = true;
else {
if (isBlankSet) {
wordCount++;
isBlankSet = false;
}
}
}
return wordCount + 1;
}
Algo in O(N)
count : 0;
if(str[0] == validChar ) :
count++;
else :
for i = 1 ; i < sizeOf(str) ; i++ :
if(str[i] == validChar AND str[i-1] != validChar)
count++;
end if;
end for;
end if;
return count;
import com.google.common.base.Optional;
import com.google.common.base.Splitter;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multiset;
String str="Simple Java Word Count count Count Program";
Iterable<String> words = Splitter.on(" ").trimResults().split(str);
//google word counter
Multiset<String> wordsMultiset = HashMultiset.create();
for (String string : words) {
wordsMultiset.add(string.toLowerCase());
}
Set<String> result = wordsMultiset.elementSet();
for (String string : result) {
System.out.println(string+" X "+wordsMultiset.count(string));
}
add at the pom.xml
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>r09</version>
</dependency>
Counting Words in a String:
This might also help -->
package data.structure.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CountWords {
public static void main(String[] args) throws IOException {
// Couting number of words in a string
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter Your String");
String input = br.readLine();
char[] arr = input.toCharArray();
int i = 0;
boolean notCounted = true;
int counter = 0;
while (i < arr.length) {
if (arr[i] != ' ') {
if (notCounted) {
notCounted = false;
counter++;
}
} else {
notCounted = true;
}
i++;
}
System.out.println("words in the string are : " + counter);
}
}
public class TestStringCount {
public static void main(String[] args) {
int count=0;
boolean word= false;
String str = "how ma ny wo rds are th ere in th is sente nce";
char[] ch = str.toCharArray();
for(int i =0;i<ch.length;i++){
if(!(ch[i]==' ')){
for(int j=i;j<ch.length;j++,i++){
if(!(ch[j]==' ')){
word= true;
if(j==ch.length-1){
count++;
}
continue;
}
else{
if(word){
count++;
}
word = false;
}
}
}
else{
continue;
}
}
System.out.println("there are "+(count)+" words");
}
}
import java.util.;
import java.io.;
public class Main {
public static void main(String[] args) {
File f=new File("src/MyFrame.java");
String value=null;
int i=0;
int j=0;
int k=0;
try {
Scanner in =new Scanner(f);
while(in.hasNextLine())
{
String a=in.nextLine();
k++;
char chars[]=a.toCharArray();
i +=chars.length;
}
in.close();
Scanner in2=new Scanner(f);
while(in2.hasNext())
{
String b=in2.next();
System.out.println(b);
j++;
}
in2.close();
System.out.println("the number of chars is :"+i);
System.out.println("the number of words is :"+j);
System.out.println("the number of lines is :"+k);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
My idea of that program is that:
package text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CoutingWords {
public static void main(String[] args) throws IOException {
String str;
int cWords = 1;
char ch;
BufferedReader buffor = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter text: ");
str = buffor.readLine();
for(int i =0; i<str.length(); i++){
ch = str.charAt(i);
if(Character.isWhitespace(ch)){ cWords++; }
}
System.out.println("There are " + (int)cWords +" words.");
}
}
I'm new to stackoverflow but I hope my code helps:
private int numOfWordsInLineCounter(String line){
int words = 0;
for(int i = 1 ; i<line.length();i++){
Character ch = line.charAt(i-1);
Character bch = line.charAt(i);
if(Character.isLetterOrDigit(ch) == true && Character.isLetterOrDigit(bch)== false ) words++;
if(i == line.length()-1 && Character.isLetterOrDigit(bch))words++;
}
return words;
}
A string phrase normaly has words separated by space. Well you can split the phrase using the spaces as separating characters and count them as follows.
import java.util.HashMap;
import java.util.Map;
public class WordCountMethod {
public static void main (String [] args){
Map<String, Integer>m = new HashMap<String, Integer>();
String phrase = "hello my name is John I repeat John";
String [] array = phrase.split(" ");
for(int i =0; i < array.length; i++){
String word_i = array[i];
Integer ci = m.get(word_i);
if(ci == null){
m.put(word_i, 1);
}
else m.put(word_i, ci+1);
}
for(String s : m.keySet()){
System.out.println(s+" repeats "+m.get(s));
}
}
}
Taking the chosen answer as a starting point the following deals with a few English language issues including hyphenated words, apostrophes for possessives and shortenings, numbers and also any characters outside of UTF-16:
public static int countWords(final String s) {
int wordCount = 0;
boolean word = false;
final int endOfLine = s.length() - 1;
for (int i = 0; i < s.length(); i++) {
// if the char is a letter, word = true.
if (isWordCharacter(s, i) && i != endOfLine) {
word = true;
// if char isn't a letter and there have been letters before,
// counter goes up.
} else if (!isWordCharacter(s, i) && word) {
wordCount++;
word = false;
// last word of String; if it doesn't end with a non letter, it
// wouldn't count without this.
} else if (isWordCharacter(s, i) && i == endOfLine) {
wordCount++;
}
}
return wordCount;
}
private static boolean isWordCharacter(final String s, final int i) {
final char ch = s.charAt(i);
return Character.isLetterOrDigit(ch)
|| ch == '\''
|| Character.getType(ch) == Character.DASH_PUNCTUATION
|| Character.isSurrogate(ch);
}
I just put this together. The incrementer in the wordCount() method is a bit inelegant to me, but it works.
import java.util.*;
public class WordCounter {
private String word;
private int numWords;
public int wordCount(String wrd) {
StringTokenizer token = new StringTokenizer(wrd, " ");
word = token.nextToken();
numWords = token.countTokens();
numWords++;
return numWords;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String userWord;
WordCounter wc = new WordCounter();
System.out.println("Enter a sentence.");
userWord = input.nextLine();
wc.wordCount(userWord);
System.out.println("You sentence was " + wc.numWords + " words long.");
}
}
create variable count, state. initialize variables
if space is present keep count as it is else increase count.
for eg:
if (string.charAt(i) == ' ' ) {
state = 0;
} else if (state == 0) {
state = 1;
count += 1;
lambda, in which splitting and storing of the counted words is dispensed withand only counting is done
String text = "counting w/o apostrophe's problems or consecutive spaces";
int count = text.codePoints().boxed().collect(
Collector.of(
() -> new int[] {0, 0},
(a, c) -> {
if( ".,; \t".indexOf( c ) >= 0 )
a[1] = 0;
else if( a[1]++ == 0 ) a[0]++;
}, (a, b) -> {a[0] += b[0]; return( a );},
a -> a[0] ) );
gets: 7
works as a status machine that counts the transitions from spacing characters .,; \t to words
if(str.isEmpty() || str.trim().length() == 0){
return 0;
}
return (str.trim().split("\\s+").length);
String a = "Some String";
int count = 0;
for (int i = 0; i < a.length(); i++) {
if (Character.isWhitespace(a.charAt(i))) {
count++;
}
}
System.out.println(count+1);
It will count white spaces. However, If we add 1 in count , we can get exact words.