Как найти количество символов в строке java

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 description1 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).length2.

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:

String s = "hi mum how are you";
int pos = s.indexOf("mum");
String textAfterMum = s.substring(pos + "mum".length());

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.

Obviously, things get a bit more complicated when you do multilingual text analysis; e.g. searching for words. But even then, if you normalize your text and parameters before you start, you can safely code in terms of “code units” rather than “code points” most of the time; i.e. length() still works.


1 – This description was on some versions of the question. See the edit history … if you have sufficient rep points.
2 – Using str.getBytes(charset).length entails doing the encoding and throwing it away. There is possibly a general way to do this without that copy. It would entail wrapping the String as a CharBuffer, creating a custom ByteBuffer with no backing to act as a byte counter, and then using Encoder.encode(...) to count the bytes. Note: I have not tried this, and I would not recommend trying unless you have clear evidence that getBytes(charset) is a significant performance bottleneck.

Теги: java, length, длина строки, сравнение длины строк

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

JavaSpec_970x90-20219-e8e90f.png

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

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


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

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

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

public class Main {

   public static void main(String args[]){
      String Str1 = new String("Добро пожаловать на сайт Otus.ru!");
      String Str2 = new String("Otus.ru" );

      System.out.print("Длина строки " Добро пожаловать на сайт Otus.ru!" - " );
      System.out.println(Str1.length());

      System.out.print("Длина строки " Otus.ru" - " );
      System.out.println(Str2.length());
   }
}

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

Длина строки " Добро пожаловать на сайт Otus.ru!" - 33
Длина строки " Otus.ru" – 7

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

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

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

public class Main {

   public static void main(String args[]) {
      // Определяем длины строки s1 и s2.
      String s1 = "В Otus я стану отличным программистом!";
      int len1 = s1.length();
      String s2 = "В Otus я стану отличным разработчиком!";
      int len2 = s2.length();

      // Вывод на экран количества символов в каждой строке.
      System.out.println( "Длина строки "В Otus я стану отличным программистом!": " + len1 + " символов.");
      System.out.println( "Длина строки "В Otus я стану отличным разработчиком!": " + len2 + " символов.");

      // Сравнение длин строк s1 и s2.
      if (len1 > len2){
          System.out.println( "nСтрока "В Otus я стану отличным программистом!" длиннее строки "В Otus я стану отличным разработчиком!".");
      }
      if (len1 < len2){
          System.out.println( "nСтрока "В Otus я стану отличным программистом!" короче строки "В Otus я стану отличным разработчиком!".");
      } 
      else {
          System.out.println( "nСтроки "В Otus я стану отличным программистом!" и "В Otus я стану отличным разработчиком!" равны.");
      }
   }
}

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

Длина строки "В Otus я стану отличным программистом!": 38 символов.
Длина строки "В Otus я стану отличным разработчиком!": 38 символов.

Строки "В Otus я стану отличным программистом!" и "В Otus я стану отличным разработчиком!" равны.

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

JavaSpec_970x550-20219-a74b18.png

Strings in Java are objects that are supported internally by a char array. Since arrays are immutable, and strings are also a type of exceptional array that holds characters, therefore, strings are immutable as well. 

The String class of Java comprises a lot of methods to execute various operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), substring() etc. Out of these methods, we will be focusing on the length() method. 

What do you mean by Length or Size of a String?

The length or size of a string means the total number of characters present in it. 

For Example: The string “Geeks For Geeks” has 15 characters (including spaces also).

String.length() method

The Java String length() method is a method that is applicable for string objects. length() method returns the number of characters present in the string. The length() method is suitable for string objects but not for arrays. 

The length() method can also be used for StringBuilder and StringBuffer classes. The length() method is a public member method. Any object of the String class, StringBuilder class, and StringBuffer class can access the length() method using the . (dot) operator.

Method Signature: The method signature of the length() method is as follows –

public int length()  

Return Type: The return type of the length() method is int.

Below are the examples of how to get the length of String in Java using the length() method:

Example 1: Java program to demonstrate how to get the length of String in Java using the length() method

Java

public class Test {

    public static void main(String[] args)

    {

        String str = "GeeksforGeeks";

        System.out.println(

            "The size of "

            + "the String is "

            + str.length());

    }

}

Output

The size of the String is 13

Example 2: Java program to illustrate how to check whether the length of two strings is equal or not using the length() method.

Java

import java.io.*;

class GFG {

    public static void main(String[] args)

    {

        String s1 = "abc";

        String s2 = "xyz";

        int len1 = s1.length();

        int len2 = s2.length();

        if (len1 == len2) {

            System.out.println(

                "The length of both the strings are equal and is " + len1);

        }

        else {

            System.out.println(

                "The length of both the strings are not equal");

        }

    }

}

Output

The length of both the strings are equal and is 3

Last Updated :
22 Dec, 2021

Like Article

Save Article

Ответы

Аватар пользователя Maksim Litvinov

Maksim Litvinov

10 марта 2022

Чтобы посчитать количество символов в строке в Java, можно воспользоваться методом строк length(). Этот метод возвращает целое число – количество символов Юникода в строке%

var word = "Hello!";
word.length(); // 6

var text = "Hello, World!";
text.length(); // 13



0



0

Добавьте ваш ответ

Рекомендуемые курсы

курс

Java: Основы ООП

35 часов

Старт в любое время

курс

Java: Автоматическое тестирование

14 часов

Старт в любое время

курс

Java: Веб-технологии

69 часов

Старт в любое время

Похожие вопросы

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


21 декабря 2021

1

ответ

  • java строки

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


23 ноября 2021

1

ответ

  • java строки

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


23 ноября 2021

1

ответ

Как перевести stringbuilder в string java


23 ноября 2021

1

ответ

How to find the length of a Java String

Follow these steps to find the length of a String in Java:

  1. Declare a variable of type String
  2. Initialize the String variable to a non-null value
  3. Call the Java String length() method
  4. Hold the value of the String length in a variable for future use

Java String length method()

The Java String class contains a length() method that returns the total number of characters a given String contains.

This value includes all blanks, spaces, and other special characters. Every character in the String is counted.

String Class JavaDoc (Java 17)
public int length() - returns the number of characters in a text string

Java String length() example

Here is a simple example of how to find the length of a String in Java and print the value out to the console:

String javaString = " String length example   "; 
int stringSize= javaString.length();
System.out.println(stringSize);
//This Java String length example prints out 25

How do I remove whitespace from a Java String’s length?

In the above example of Java’s String length method, the output for the size of the String is 25. The String length method includes the whitespace padding at the beginning and the end of the String.

Quite often, when validating input or manipulating text, you want to eliminate leading and trailing whitespace. This can be achieved through the use of the Java String’s trim method.

String javaString = " String length example ";
int stringSize= javaString.trim().length();
System.out.println(stringSize);
//This Java String length trim example prints out 21

As you can see with the example above, the whitespaces are not included in the calculation of the length of a String when the trim method is called first.

Java String length() companion methods

String method Method function
trim() removes whitespace before the Java String’s length method is called
charAt(int index) Returns the character at a given position in a String
toUpperCase() Converts all characters in a String to uppercase
toLowerCase() Converts all characters in a String to lowercase
substring(int index) Returns a subset of the Java String

String length method vs property

Be careful not to confuse the String length() method with the length property of an array.

The Java String length() method of an array is followed by round brackets, while the Java String length property is not.

Developers often confuse the Java String length method with the length property of an array.

String length compile errors

If you leave the round brackets off the Java String’s length method, the following compile time error results:

Java String error: length cannot be resolved or is not a field

Also be sure to initialize the Java String before you invoke the length() method, or else a NullPointer runtime exception results.

To find the length of a String, make sure you invoke the length() method, not the length property.

Advanced Java String length example

There are many scenarios where a program must first find the length of a Java String.

Here is a rather advanced piece of code that checks to see if a given String is a palindrome. I used a variety of methods from the String class, including length(), charAt() and substring().

package com.mcnz.servlet;

/* Find the length of a Java String example */
public class JavaPalindromeCheckProgram {

  public static void main(String[] args) {
    boolean flag = palindromeCheck("amanaplanacanalpanama");
    System.out.println(flag);
  }
  /* This code uses the Java String length method in its logic */
  public static boolean palindromeCheck(String string){
    /* check if the Java String length is zero or one */
    if(string.length() == 0 || string.length() == 1) {
      return true;
    }
    if(string.charAt(0) == string.charAt(string.length()-1)) {
      return palindromeCheck(string.substring(1, string.length()-1));
    }
    return false;
  }
}

Using Java’s String length method

To get the number of characters in a given piece of text, the Java String length() method is all you need.

Just make sure the String is not null, and avoid any confusion between Java’s length vs length() constructs, and you will have no problem manipulating text Strings in Java.

Добавить комментарий