声明一个整数,将其初始化为0,然后为每个字符递增循环。
public class Sample { public static void main(String args[]) { String str = new String("Hi welcome to Nhooo"); 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