您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

使用 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
java 2022/1/1 18:27:09 有507人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶