如何编写Java函数以计算字符串的长度?
发布时间:2023-09-24 23:52:40
你可以使用Java的内置字符串函数length()来计算字符串的长度。下面是一个示例函数,用于计算给定字符串的长度:
public class StringUtils {
public static int calculateLength(String str) {
if (str == null) {
return 0;
}
return str.length();
}
public static void main(String[] args) {
String testString = "Hello, World!";
int length = calculateLength(testString);
System.out.println("Length of the string is: " + length);
}
}
在上面的例子中,calculateLength函数接受一个字符串作为参数,并使用length()方法返回其长度。首先,函数检查字符串是否为null,如果是,则返回0。如果字符串不为空,则返回字符串的长度。在main函数中,我们将一个测试字符串传递给calculateLength函数,并输出结果。
运行上述代码将输出:Length of the string is: 13,表示给定字符串的长度为13。
