在java中,切换字符串中的字符同时将其余字符保留在其原始位置的最佳方法是什么? 我真正关心的是除了以下方法之外是否还有其他方法可以处理此索引超出范围错误: 假设您想将“stringExample”中的字母 r 与大写 E 交换。
你可以将其分成“st”+“r”+“ing”+“E”+“xample”
---------------------------->(0,i)--(i,i+1)--(i +1,k)--(k,k+1)---(k+1)
然后切换“r”和“E”:“st”+“E”+“ing”+“r”+“xample”
---------------------------->(0,i)--(k,k+1)--( i+1,k)--(i,i+1)---(k+1)
唯一的问题是,如果 k 是最后一个索引,那么您需要编写一个 if 语句来捕获此异常。除了按照我之前建议的操作之外,是否有更好的方法来切换这些字母?
最佳答案
如果您只想替换字符串中的字符,那么最好使用 String.substring 完全重建字符串。 。例如:
String swapLetters(String str, int firstIndex, int secondIndex) {
if (firstIndex < 0 || firstIndex >= str.length()) {
throw new IndexOutOfBoundsException("firstIndex '" + firstIndex + "' is out of bounds.");
} else if (secondIndex < 0 || secondIndex >= str.length()) {
throw new IndexOutOfBoundsException("secondIndex '" + secondIndex + "' is out of bounds.");
} else if (firstIndex >= secondIndex) {
throw new IndexOutOfBoundsException("firstIndex isn't before secondIndex");
}
StringBuilder newString = new StringBuilder(str.substring(0, firstIndex));
newString.append(str.charAt(secondIndex)).append(str.substring(firstIndex + 1, secondIndex))
.append(str.charAt(firstIndex)).append(str.substring(secondIndex + 1));
return newString.toString();
}
在这里,即使它是最后一个字母,子字符串也只会返回一个空字符串,这样就可以了。
System.out.println("stringExample becomes " + swapLetters("stringExample", 2, 12)); //--> stringExample becomes steingExamplr
System.out.println("stringExample becomes " + swapLetters("stringExample", 2, 6)); //--> stringExample becomes stEingrxample
如果您只想替换给定字母中每个字母的第一个实例,您可以使用 indexOf('r')
而不是 charAt(2)
,例如示例。
关于Java列表索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40066234/