Количество букв string java

Как посчитать количество букв в строке java

Чтобы посчитать количество букв в строке, можно использовать метод строк length() . Этот метод вернет длину строки:

var word = "Hello"; var lettersCount = word.length(); System.out.println(lettersCount); // 5 

Если строка содержит не только буквы, но и другие символы, а посчитать надо буквы, то можно так :

String word = "a1B2c!D%"; int lettersCount = 0; for (int i = 0; i  word.length(); i++)  if (Character.isAlphabetic(word.charAt(i)))  lettersCount++; > > System.out.println(lettersCount); // => 4 

Источник

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 Characters in a String in Java

Count Characters in a String in Java

  1. Use String.length() to Count Total Characters in a Java String
  2. Use Java 8 Stream to Count Characters in a Java String
  3. Use Loop and charAt() to Count a Specific Character in a Java String

Today, we will introduce multiple ways to count the characters in a given Java string. We will count the total characters and the specific characters.

Use String.length() to Count Total Characters in a Java String

The most common practice to get the total count of characters in a Java string is to use the length() method. In the below code, we have a string exampleString and will use exampleString.length() to get this string’s total length.

The output shows that there are 28 characters in exampleString while there are only 23 characters. It happens because String.length() counts the whitespaces too. To tackle this problem, we can use the replace() function to replace all the whitespaces with an empty character that is not counted. Finally, we can get the length of the string without any whitespaces, which is 23.

public class CountCharsInString   public static void main(String[] args)    String exampleString = "This is just a sample string";   int stringLength = exampleString.length();   System.out.println("String length: " + stringLength);   int stringLengthWithoutSpaces = exampleString.replace(" ", "").length();  System.out.println("String length without counting whitespaces: " + stringLengthWithoutSpaces);  > > 
String length: 28 String length without counting whitespaces: 23 

Use Java 8 Stream to Count Characters in a Java String

Another way to count all the characters in a string is to use the String.chars().count() method that returns the total number of characters in the string, but including whitespaces. As chars() is a stream, we can use the filter() method to ignore the whitespaces. filter(ch -> ch != ‘ ‘) checks every character and if it founds a whitespace it will filter it out.

public class CountCharsInString   public static void main(String[] args)    String exampleString = "This is just a sample string";   long totalCharacters = exampleString.chars().filter(ch -> ch != ' ').count();   System.out.println("There are total " + totalCharacters + " characters in exampleString");  > > 
There are total 23 characters in exampleString 

Use Loop and charAt() to Count a Specific Character in a Java String

We have been counting the total characters in a string, but the below example shows the method to count a specific character in the string. Our goal is to get the number of i in exampleString . To achieve this, we used a loop that runs until the string’s end.

We create two additional variables: totalCharacters that will hold the count, and temp that will hold every individual character using exampleString.charAt(i) . To check our character’s occurrence, we will compare temp with our character to check if they match. If it finds a match, then totalCharacters will be incremented by one. Once the loop is over, we can see the total occurrences of our character in the string.

public class CountCharsInString   public static void main(String[] args)    String exampleString = "This is just a sample string";   int totalCharacters = 0;  char temp;  for (int i = 0; i  exampleString.length(); i++)    temp = exampleString.charAt(i);  if (temp == 'i')  totalCharacters++;  >   System.out.println("i appears " + totalCharacters + " times in exampleString");  > > 
i appears 3 times in exampleString 

Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.

Related Article — Java String

Related Article — Java Char

Copyright © 2023. All right reserved

Источник

Читайте также:  таблицы
Оцените статью