Java中如何实现字符串长度函数?
发布时间:2023-09-14 04:49:24
在Java中,可以使用String类的length()方法来获取字符串的长度。length()方法返回的是字符串中字符的数量。例如,下面的代码演示了如何实现一个获取字符串长度的函数:
public class StringLength {
public static int getStringLength(String str) {
return str.length();
}
public static void main(String[] args) {
String str = "Hello, World!";
int length = getStringLength(str);
System.out.println("The length of the string is: " + length);
}
}
输出结果为:
The length of the string is: 13
在上面的代码中,getStringLength()方法接收一个字符串作为参数,并使用该字符串的length()方法获取字符串的长度。最后,在main方法中调用getStringLength()方法并打印输出字符串的长度。
