【问题标题】:What is wrong in using charAt function in this context?在这种情况下使用 charAt 函数有什么问题?
【发布时间】:2015-07-10 07:52:02
【问题描述】:

我试图用这种方式复制一个单词。我不确定,我是按照正确的方式处理String

代码是:

 public static void main(String args[])
   {
      String str="Hello";
      int i=0;
      String copy = "";
      while (str.charAt(i) !='\0')
      {
          copy = copy + str.charAt(i);
          i++;
      }

      System.out.println(copy);
   }

运行此代码会产生Exception

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 5
    at java.lang.String.charAt(Unknown Source)
    at ReverseWord.main(ReverseWord.java:15)

我是否使用charAt() 并以正确的方式检查null?或者,我对String 处理Java 有错误的概念?

【问题讨论】:

  • 你对字符串处理有一个错误的概念。它们不是 0 终止的。 String.length() 给你尺寸。
  • 另外,以前的字符串拼接方式比较费钱,不知道以后的Java版本有没有改过。
  • 为什么要复制一个字符串?试试这个String str2 = new String(str);。并在此处阅读有关字符串池的信息:stackoverflow.com/questions/2486191/…

标签: java string


【解决方案1】:

您以错误的方式使用Strings(对于Java!)让我们澄清一些在Java中使用String的基本要点:

  • String 是不可变的。这意味着每次修改它JVM 都会创建一个新对象。这是很多资源,因此,为了更好地编程,您不应该在Strings 中使用串联,而是使用StringBuilder 进行串联。
  • Strings 不以任何特殊符号结尾,这可能发生在某些文件类型中,但不会发生在 Strings 对象中,因此您必须使用 length() 获取大小并在必要时使用它进行迭代。
  • 始终在任何 Java 对象的 API 处循环以了解其功能:
    StringAPI7
    StringAPI8
  • 要按字符循环 String 字符,您可以使用 forwhile 和其他几种方法(拆分、转换...):

For循环示例:

for (int i = 0; i < str.length(); i++)

虽然例子:

while (i < str.length()) {

说...看看这段代码的工作使用解释的内容:

public static void main(String[] args) {
    String str = "Hello";
    int i = 0;
    // string builder is a mutable string! :)
    StringBuilder copy = new StringBuilder();
    // we iterate from i=0 to length of the string (in this case 4)
    while (i < str.length()) {
        // same than copy = copy + str.charAt(i)
        // but not creating each time a new String object
        copy.append(str.charAt(i));
        // goto next char
        i++;
    }

    // print result 
    System.out.println(copy);
}

更新

谢谢...但是当我试图找到反向时没有得到结果

如果您想要反转String(您的代码没有这样做,您必须编写copy = str.charAt(i) + copy;)使用StringBuilder 更容易。看看这个例子:

public static void main(String[] args) {
    String str = "Hello";
    StringBuilder copy = new StringBuilder(str);
    copy.reverse();
    System.out.println(copy);
}

【讨论】:

  • 检查我的更新...您的代码没有反转String...但在我的更新中您会发现新代码反转String
【解决方案2】:

第一种方式:

使用下面的代码:

for (int i = 0; i < str.length(); i++) {
    copy = copy+str.charAt(i);
}

第二种方式:

String 转换为char[]。然后将其转换回String

char[] ch = str.toCharArray();
String copy = new String(ch);
System.out.println(copy);

【讨论】:

  • 我想让OP理解..我们可以通过多种方式做到这一点。
  • 对我来说,for 循环更容易理解,但很多人对 while 的看法相同,所以我猜 OP 对while 循环感觉更舒服...
猜你喜欢
  • 2017-07-09
  • 1970-01-01
  • 2016-05-12
  • 2022-01-23
  • 1970-01-01
  • 1970-01-01
  • 2015-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多