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

от admin

Strings

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings

The most direct way to create a string is to write:

In this case, "Hello world!" is a string literal—a series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value—in this case, Hello world! .

As with any other object, you can create String objects by using the new keyword and a constructor. The String class has thirteen constructors that allow you to provide the initial value of the string using different sources, such as an array of characters:

The last line of this code snippet displays hello .

String Length

Methods used to obtain information about an object are known as accessor methods. One accessor method that you can use with strings is the length() method, which returns the number of characters contained in the string object. After the following two lines of code have been executed, len equals 17:

A palindrome is a word or sentence that is symmetric—it is spelled the same forward and backward, ignoring case and punctuation. Here is a short and inefficient program to reverse a palindrome string. It invokes the String method charAt(i) , which returns the i th character in the string, counting from 0.

Running the program produces this output:

To accomplish the string reversal, the program had to convert the string to an array of characters (first for loop), reverse the array into a second array (second for loop), and then convert back to a string. The String class includes a method, getChars() , to convert a string, or a portion of a string, into an array of characters so we could replace the first for loop in the program above with

Concatenating Strings

The String class includes a method for concatenating two strings:

This returns a new string that is string1 with string2 added to it at the end.

You can also use the concat() method with string literals, as in:

Strings are more commonly concatenated with the + operator, as in

which results in

The + operator is widely used in print statements. For example:

Such a concatenation can be a mixture of any objects. For each object that is not a String , its toString() method is called to convert it to a String .

Breaking strings between lines using the + concatenation operator is, once again, very common in print statements.

Creating Format Strings

You have seen the use of the printf() and format() methods to print output with formatted numbers. The String class has an equivalent class method, format() , that returns a String object rather than a PrintStream object.

Using String's static format() method allows you to create a formatted string that you can reuse, as opposed to a one-time print statement. For example, instead of

How to Count Characters in a String in Java?

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:

  • for loop
  • length() method
  • chars.count() method
  • charAt() method

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:

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:

Output

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.

How to correctly compute the length of a String in Java?

I know there is String#length and the various methods in Character which more or less work on code units/code points.

What is the suggested way in Java to actually return the result as specified by Unicode standards (UAX#29), taking things like language/locale, normalization and grapheme clusters into account?

5 Answers 5

The normal model of Java string length

String.length() is specified as returning the number of char values ("code units") in the String. That is the most generally useful definition of the length of a Java String; see below.

Your description 1 of the semantics of length based on the size of the backing array/array slice is incorrect. The fact that the value returned by length() is also the size of the backing array or array slice is merely an implementation detail of typical Java class libraries. String does not need to be implemented that way. Indeed, I think I’ve seen Java String implementations where it WASN’T implemented that way.

Alternative models of string length.

To get the number of Unicode codepoints in a String use str.codePointCount(0, str.length()) — see the javadoc.

To get the size (in bytes) of a String in a specific encoding (i.e. charset) use str.getBytes(charset).length 2 .

To deal with locale-specific issues, you can use Normalizer to normalize the String to whatever form is most appropriate to your use-case, and then use codePointCount as above. But in some cases, even this won’t work; e.g. the Hungarian letter counting rules which the Unicode standard apparently doesn’t cater for.

Using String.length() is generally OK

The reason that most applications use String.length() is that most applications are not concerned with counting the number of characters in words, texts, etcetera in a human-centric way. For instance, if I do this:

it really doesn’t matter that "mum".length() is not returning code points or that it is not a linguistically correct character count. It is measuring the length of the string using the model that is appropriate to the task at hand. And it works.

Длина строки в Java. Метод length()

В этой статье мы поговорим про метод length() . Он позволяет определять длину строк в Java и сравнивать длины этих строк между собой. Давайте посмотрим, как это делается.

Описание метода

Вышеупомянутый метод length() возвращает длину строки в Java, при этом длина определяется, как равная числу шестнадцатиразрядных Юникод-символов в исследуемой строке. Метод использует довольно простой синтаксис:

Таким образом, возвращается длина последовательности символов. Но давайте лучше посмотрим, как это происходит на примерах.

Определяем длину строки в Java

Итак, у нас есть строка, в которой надо определить длину:

Консольный вывод будет следующим:

Вы можете проверить работу этого метода самостоятельно, используя любой онлайн-компилятор Java, например, этот.

Сравниваем длины строк в Java

Метод length() позволяет не только узнать длину строк, но и сравнить их длины. Вот, как это можно реализовать:

Получим следующий результат:

В результате метод length() позволяет нам как узнать длину строки, так и сравнить несколько строк. Но, как вы уже заметили, это был простейший код. Если же вы хотите прокачать навыки Java-разработчика на более продвинутом уровне, добро пожаловать на курс не для новичков:

Похожие статьи