小编典典

在不使用 Java 中的任何内置方法的情况下查找字符串的长度?

java

在不使用 Java 中的任何内置方法的情况下查找字符串的长度?


阅读 337

收藏
2021-06-15

共1个答案

小编典典

使用 toCharArray 是最简单的解决方案。

使用 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
2021-06-15