在Java中不使用length()方法查找字符串的长度
时间:2020-01-09 10:35:27 来源:igfitidea点击:
在采访中,有时会要求人们编写Java程序来查找字符串长度,而不使用Java String类的length()方法。
在Java中,有两种方法可以不使用length方法来查找String的长度。我们可以将传递的字符串转换为char数组,并对其进行迭代以获取字符数,该字符数将为String的长度。
如果允许我们使用除length()方法之外的任何其他Java API方法,则还可以使用String类的lastIndexOf()方法获取字符串的长度。
Java代码无需使用length方法即可查找String的长度
public class StringLength {
public static void main(String[] args) {
int strLen = strLengthWithArray("Test Line");
System.out.println("Length of the String- " + strLen);
System.out.println("----------------------");
strLen = strLengthWithIndex("Test Line with index");
System.out.println("Length of the String- " + strLen);
}
private static int strLengthWithArray(String str){
char[] charArr = str.toCharArray();
int count = 0;
for(char c : charArr){
count++;
}
return count;
}
private static int strLengthWithIndex(String str){
int count = str.lastIndexOf("");
return count;
}
}
输出:
Length of the String- 9 --------------------- Length of the String- 20

