使用 tocharArray 方法将字符串转换为字符数组 迭代 char 数组并递增长度变量。
class LenghtOfStringMain{
public static void main(String args[]){
String helloWorld="This is hello world";
System.out.println("length of helloWorld string :"+getLengthOfStringWithCharArray(helloWorld));
}
public static int getLengthOfStringWithCharArray(String str)
{
int length=0;
char[] strCharArray=str.tocharArray();
for(char c:strCharArray)
{
length++;
}
return length;
}
当你运行上面的程序时,你会得到以下输出:
length of helloWorld string :19
使用 Stringindexoutofboundsexception
您一定想知道我们如何Stringindexoutofboundsexception
在不使用 length() 方法的情况下使用查找字符串的长度。请参考以下逻辑: 逻辑 初始化i与0和叠代的字符串不指定任何条件。所以它永远是真的。 一旦值i超过 String 的长度,就会抛出Stringindexoutofboundsexception
异常。 我们将catch异常并在出catch块后返回 i 。 程序
class LenghtOfStringMain{
public static void main(String args[]){
String helloWorld="This is hello world";
System.out.println("length of helloWorld string :"+getLengthOfString(helloWorld));
}
public static int getLengthOfString(String str)
{
int i=0;
try{
for(i=0;;i++)
{
str.charAt(i);
}
}
catch(Exception e)
{
}
return i;
}
当你运行上面的程序时,你会得到以下输出:
length of helloWorld string :19