Java 中求字符串长度的函数是 length(),它返回字符串中字符的数量但不包括终止符 \0。用法:String str = "Example"; int length = str.length(); 返回结果 length = 7。
Java 中求字符串长度的函数:length()
在 Java 中,求字符串长度的函数是 length()。该函数返回字符串中字符的数量,不包括终止符 \0。
用法:
String str = "Hello, world!"; int length = str.length(); // length = 13
示例:
以下代码片段演示了如何使用 length() 函数:
import java.util.Scanner; public class StringLengthDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter a string: "); String str = scanner.nextLine(); int length = str.length(); System.out.println("The length of the string is: " + length); } }
在终端中运行此代码,用户将被提示输入一个字符串。输入字符串后,将计算并打印其长度。
注意:
- 空字符串的长度为 0。
- 字符串中包含换行符 (
\n) 或制表符 (\t) 时,这些字符也将计入长度。

nner;
public class StringLengthDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string: ");
String str = scanner.nextLine();
int length = str.length();
System.out.println("The length of the string is: " + length);
}
}






