要计算字符串的长度,请将字符串转换为字符数组,然后计算数组中元素的数量。
public class StringLength {
public static void main(String args[]) throws Exception {
String str = "sampleString";
int i = 0;
for(char c: str.toCharArray()) {
i++;
}
System.out.println("Length of the given string ::"+i);
}
}输出结果
Length of the given string ::12