如何在java中查找长度而不使用length()方法
时间:2020-02-23 14:34:11 来源:igfitidea点击:
"如何在不使用length()方法的情况下"如何在Java中查找长度。
有很多方法可以找到字符串的长度。
他们之中有一些是 :
使用tochararray是最简单的解决方案。
使用tochararray
逻辑
- 使用tochararray方法将字符串转换为char数组
- 迭代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在不使用长度()方法的情况下,查找字符串的长度。
请参阅以下逻辑:
逻辑
- 初始化
i和0并迭代字符串而不指定任何条件。所以它总是如此。 - 一旦价值
i将超过字符串的长度,它会抛出StringIndexOutOfBoundsException例外。 - 我们将
catch出来后,我出现了一个例外并返回catch堵塞。
程序
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

