栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在不使用 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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/366964.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号