Count string character in java

Counting the number of occurences of characters in a string [duplicate]

I am trying to write a Java program which takes in as input a string and counts the number of occurrences of characters in a string and then prints a new string having the character followed by the no of occurrences.

E.G.

/*Write a routine that takes as input a string such as "aabbccdef" and o/p "a2b2c2def" or "a4bd2g4" for "aaaabddgggg".*/ import java.util.Scanner; public 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(); while(str.length()>0) < ch=str.charAt(0); int i=0; while(str.charAt(i)==ch) < count =count+i; i++; >str.substring(count); System.out.println(ch); System.out.println(count); > > > 

How about adding the algorithm tag? This is actually an easy question for the group. The problem seems like an interview question, also a tag.

7 Answers 7

That will keep going until it falls off the end. when i is the same as the length of the string, it will be asking for a character beyond the end of the string. You probably want:

Читайте также:  Сколько весит python программа

You also need to set count to 0 at the start of each iteration of the bigger loop — the count resets, after all — and change

. or get rid of count or i . They’re always going to have the same value, after all. Personally I’d just use one variable, declared and initialized inside the loop. That’s a general style point, in fact — it’s cleaner to declare local variables when they’re needed, rather than declaring them all at the top of the method.

However, then your program will loop forever, as this doesn’t do anything useful:

Strings are immutable in Java — substring returns a new string. I think you want:

Note that this will still output «a2b2a2» for «aabbaa». Is that okay?

@user1262062: I’ve given you enough hints now, I think. I assume this is homework — I’ve told you everything you should need to fix it. You need to put in effort yourself to work out what’s going wrong — if I just give you the complete code, you won’t learn much, will you? (I’d also strongly suggest that you work on communicating using full words rather than «text-speak» which makes everyone’s life harder. Communication is incredibly important in software engineering.)

If this is an answer for your interview, you have to impress the company with the best and simplest code to understand. Perfection may not be expected, but I know there’s an easier code solution (see my answer below). A link is at www.careercup.com.

public class StringTest < public static void main(String[] args)< String s ="aaabbbbccccccdd"; String result=""; StringBuilder sb = new StringBuilder(s); while(sb.length() != 0)< int count = 0; char test = sb.charAt(0); while(sb.indexOf(test+"") != -1)< sb.deleteCharAt(sb.indexOf(test+"")); count++; >//System.out.println(test+" is repeated "+count+" number of times"); result=result+test+count; > System.out.println(result); > > 

I don’t want to give out the full code. So I want to give you the challenge and have fun with it. I encourage you to make the code simpler and with only 1 loop.

Basically, my idea is to pair up the characters comparison, side by side. For example, compare char 1 with char 2, char 2 with char 3, and so on. When char N not the same with char (N+1) then reset the character count. You can do this in one loop only! While processing this, form a new string. Don’t use the same string as your input. That’s confusing.

Remember, making things simple counts. Life for developers is hard enough looking at complex code.

Tommy «I should be a Teacher» Kwee

Источник

How to Count Characters in a String in Java?

While programming in Java, there exist chances that you need to check the total number of characters of the specified string. In such a scenario, you must count the string characters to determine their length. This functionality can also be utilized in several Java applications where it is required to delete unwanted or duplicated characters of a string.

This tutorial will describe the methods to count the characters in strings in Java.

How to Count Characters in a String in Java?

To count the string’s characters, there are some methods listed as follows:

We will now check out each of the above-mentioned methods one by one.

Method 1: Count Characters in a String in Java Using for Loop

Using the “for” loop for counting the characters of a string is the simplest method utilized by programmers. This method will iterate according to the string’s length and count its characters.

Example
In this example, we will count the characters of the string with white spaces. For this purpose, we will create a String type variable named “string” and an integer type variable named “chCount” initialized with value 0:

String string = «Welcome To Linux Hint” ;
System.out.println(» String : » + string);

Then, we will iterate the string until the length of the string using for loop and count the characters “chCount” increment value:

Lastly, we will print the value of the “chCount” variable:

In the defined string, there are 18 characters and three spaces. Therefore, the output displayed “21” as the total number of string characters, including spaces:

Want to try out Java methods for counting characters? Have a look at the below-given sections.

Method 2: Count Characters in a String in Java Using String.length() Method

Another method to count a character in a string is the “length()”. This method belongs to the String class; that’s why it is called using the String class object.

Example
In this example, we will consider two cases:

  • Counting string characters including white spaces
  • Counting string characters without spaces

For the first case, we will create an integer type variable named “newString” that stores the length of the full string by calling the “string.length()” method. This method will count the characters of “newString” including the whitespaces:

int newString = string.length();
System.out.println(“The Characters in the String including spaces: ” + newString);

Now, we will find the count of the characters of a string without spaces. For that, we will call the “replace()” method of the String class with the “length()” method. The replace() method accepts two parameters that will neglect the spaces from the string and returns the count of the characters using the length() method:

int newStrng = string. replace ( » » , «» ) . length ( ) ;
System . out . println ( «The Characters in the String without spaces: » + newStrng ) ;

The output shows the 21 as characters count, including spaces, while without spaces, the count of the character is 18:

Let’s check out the third method!

Method 3: Count Characters in a String in Java Using String.chars.count() Method

The “String.chars().count()” method returns the number of characters present in the string, with white spaces. Additionally, we will use the “filter()” method to count characters without spaces.

Example
In this method, we will count the characters of our “strng” String without spaces by utilizing the “String.chars.filter().count()” method:

Do you only want to count the numbers of a particular character occurrence? Check out the following section!

Method 4: Count Characters in a String in Java Using charAt() Method

In a Java program, the “charAt()” method is used if you want to find the occurrence of a specific character in a string.

Example
In this example, we will check how many times the character “n” appears in the string. For this purpose, we will again use the same string that is used in the above example and create an integer type variable “chCount” initialized with “0”, and a character type variable named “findChar” initialized with character “n”:

Now, we will iterate the string until the full length of the string using “for” loop and match every character with “findChar” that is “n” and increment the count if the added condition is evaluated as true, otherwise move to the next iteration:

Lastly, print the character count:

System.out.println(«The Character ‘» +findChar+ «‘ in the String is ‘» +chCount+ «‘ times»);

The given output states that in the “strng” String, the “n” character occurred two times:

We compiled all the necessary information on how to count the characters in a string in Java.

Conclusion

To count characters in a string in Java, there are different methods: using for loop, charAt() method, String.chars.count() method, and the String.length() method. You can count characters from strings, including spaces, without spaces, and the occurrence of the specific character in a string by using these methods. This tutorial discussed the methods to count characters in a string in Java.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

Count number of each char in a String

You guys will probably laugh at the way that I implemented this simple task. I know there is a simpler way of doing this but I just really cant think of it right now. Can you guys please help me out?

String sample = "hello world"; char arraysample[] = sample.toCharArray(); int length = sample.length(); //count the number of each letter in the string int acount = 0; int bcount = 0; int ccount = 0; int dcount = 0; int ecount = 0; int fcount = 0; int gcount = 0; int hcount = 0; int icount = 0; int jcount = 0; int kcount = 0; int lcount = 0; int mcount = 0; int ncount = 0; int ocount = 0; int pcount = 0; int qcount = 0; int rcount = 0; int scount = 0; int tcount = 0; int ucount = 0; int vcount = 0; int wcount = 0; int xcount = 0; int ycount = 0; int zcount = 0; for (int i = 0; i < length; i++) < char c = arraysample[i]; switch (c) < case 'a': acount++; break; case 'b': bcount++; break; case 'c': ccount++; break; case 'd': dcount++; break; case 'e': ecount++; break; case 'f': fcount++; break; case 'g': gcount++; break; case 'h': hcount++; break; case 'i': icount++; break; case 'j': jcount++; break; case 'k': kcount++; break; case 'l': lcount++; break; case 'm': mcount++; break; case 'n': ncount++; break; case 'o': ocount++; break; case 'p': pcount++; break; case 'q': qcount++; break; case 'r': rcount++; break; case 's': scount++; break; case 't': tcount++; break; case 'u': ucount++; break; case 'v': vcount++; break; case 'w': wcount++; break; case 'x': xcount++; break; case 'y': ycount++; break; case 'z': zcount++; break; >> System.out.println("There are " + hcount + " h's in here "); System.out.println("There are " + ocount + " o's in here "); 

@Raedwald: Not entirely. The question is probably not to review this code but how to work with arrays (a large number of variables). In that sense it’s a technical question.

Источник

Java — Count number of symbols in string

the simplest way would be iterate through the String and count them.

int commas = 0; for(int i = 0; i < helloWorld.length(); i++) < if(helloWorld.charAt(i) == ',') commas++; >System.out.println(helloWorld + " has " + commas + " commas!"); 
int numberOfCommas = helloWorld .replaceAll("[^,]","").length(); 

More implementation you can find in this site

String[] tokens = helloWorld.split(","); System.out.println("Number of commas: " + (tokens.length - 1)); 

This is not very helpful. Suppose the string is «One, Two, Thre. » split won’t count the las commas. As the javadoc of the class String says Trailing empty strings are therefore not included in the resulting array.

Not so simple but shorter way

String str = "One,Two,Three,Four!"; int num = str.replaceAll("[^,]","").length(); 

If you can import com.lakota.utils.StringUtils then it’s so simple. Import this> import com.lakota.utils.StringUtils;

int count = StringUtils.countMatches("One,Two,Three,Four!", ","); System.out.println("total comma "+ count); 
int count = StringUtils.countMatches("elephant", "e"); assertEquals(2, count); 
String someString = "elephant"; long count = someString.chars().filter(ch -> ch == 'e').count(); assertEquals(2, count); long count2 = someString.codePoints().filter(ch -> ch == 'e').count(); assertEquals(2, count2); 

Источник

Оцените статью