在这种情况下使用charAt函数有什么问题?

时间:2015-07-10 07:52:03

标签: java string

我试图用这种方式复制一个单词。我不确定,我正在按照正确的方式处理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处理有错误的概念?

2 个答案:

答案 0 :(得分:4)

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

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

For循环示例:

while

虽然例子:

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

答案 1 :(得分:1)

第一种方式:

使用以下代码:

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);
相关问题