如何计算 Java 字符串中的字符数?
声明一个整数,用 0 初始化,然后在 for 循环中为每个字符递增该整数。
示例
public class Sample {
public static void main(String args[]) {
String str = new String("Hi welcome to Tutorialspoint");
int count = 0;
for(int i = 0; i<str.length(); i++) {
count++;
}
System.out.println("Number characters in the given string (including spaces) "+count);
}
}输出
Number characters in the given string (including spaces) 28
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP