import java.util.Scanner;
public class Demo09 {
public static void main(String[] args) {
// 键盘录入字符
System.out.println("请输入一个字符串:");
String s = new Scanner(System.in).nextLine();
// 调用方法
getCharLength(s);
}
// getCharLength()方法求字符串长度
public static void getCharLength(String s) {
// 计数器
int count = 0;
// 将接收的字符串转换存储到字符串数组之中
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
count++;
}
System.out.println("该字符串共有" + count + "个字符.");
}
}
1.定义一个方法,求一个字符串的长度,不能使用String的length()方法 2.在main函数中输入字符串,并输出其长度
最新推荐文章于 2022-12-14 15:00:40 发布