Java字符串索引在for循环中越界(codingbat函数mirrorEnds)

标签 java string

我有一个关于String 3中codingbat问题的问题。问题如下:

Given a string, look for a mirror image (backwards) string at both the beginning and end of the given string. In other words, zero or more characters at the very begining of the given string, and at the very end of the string in reverse order (possibly overlapping).

例如,字符串“abXYZba”的镜像结尾为“ab”

mirrorEnds("abXYZba") → "ab"

mirrorEnds("abca") → "a"

mirrorEnds("aba") → "aba"

我的代码如下:

public String mirrorEnds(String string) {

if(string.length() <=1) return string;  
String x = "";
int y = string.length() - 1;


for(int i = 0; i < string.length()/2; i++)
{ 
  if(string.charAt(i) == string.charAt(y))
  {
    x+= Character.toString(x.charAt(i)); 
    y--;
  }
  else
  {
    return x;
  }
  
}

return string;

}

当我尝试执行以下操作时:

"xxYxx"

字符串长度为 5,因此索引为 0-4。如果我在我的代码上运行它,逻辑将是:

    i = 0 and y = 4;

string.charAt(i) == string.charAt(y) //true and i++ and y--
string.charAt(i) == string.charAt(y) //true and i++ and y--
//i is == string.length()/2 at this point

但是这个问题向我抛出了一个错误,指出indexoutofbounds。为什么会这样?

最佳答案

您正在访问错误字符串的第 i 个字符:

x += Character.toString(x.charAt(i));

字符串x一开始是空的,因此索引0处的字符不存在。

改为访问原始字符串

x += Character.toString(string.charAt(i));

关于Java字符串索引在for循环中越界(codingbat函数mirrorEnds),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31038868/

相关文章:

java - feign.RetryableException 包装了哪些异常?

java - 如何在eclipse(part2)中配置javadb?

string - 如何将结构中的字符串与文字进行模式匹配

C: strchr() 和 index() 的区别

java - 使用字符串的多态性和创建对象

java - 如何从 tomcat 的 lib 目录加载类路径资源?

java - public synchronized void run() 是一个坏主意吗?

c - 在 C x86 错误中反转字符串

c - strcmp 输出之谜 - strcmp 实际上是如何比较字符串的?

android - 在 Android 字符串中使用可翻译的目的是什么?