java 在Java中交换字符串的第一个和最后一个字母?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15848281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swapping the first and the last letter of a string in Java?
提问by Kimmm
int length = s.length();
if (length <= 1){
return s;
}
else {
return s.charAt(length) + s.substring(1, length-1) + s.charAt(0);
}
I'm just trying to swap the first letter and the last letter of a string.
我只是想交换字符串的第一个字母和最后一个字母。
eg. apple -> eppla
例如。苹果 -> eppla
It compiled fine and works fine with an empty string or a string with one character only. But with strings with several characters, it says:
它编译得很好,并且可以很好地处理空字符串或只有一个字符的字符串。但是对于包含多个字符的字符串,它说:
StringIndexOutOfBoundsException occured - see console for stack trace
Does tht mean there's something wrong with my code???
这是否意味着我的代码有问题???
回答by Lasse Espeholt
Try this:
试试这个:
int length = s.length();
if (length <= 1) {
return s;
} else {
return s.charAt(length - 1) + s.substring(1, length - 1) + s.charAt(0);
}
The difference is s.charAt(length - 1)
. Remember, the string is zero-indexed, so the last character is s.charAt(length - 1)
.
不同之处在于s.charAt(length - 1)
。请记住,字符串是零索引的,因此最后一个字符是s.charAt(length - 1)
.
回答by James OB
you want s.charAt(length - 1) to start off
你想要 s.charAt(length - 1) 开始
回答by user3202215
if(str.length()<=1){return str;}
String middle=str.substring(1,str.length()-1);
return str.charAt(str.length()-1)+middle+str.charAt(0);
回答by Pankaj
String str;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the String");
str=sc.nextLine();
String word[]=str.split(" ");
int len=word.length;
String temp=word[0];
word[0]=word[len-1];``
word[len-1]=temp;
for (int i = 0; i < word.length; i++) {
System.out.print(word[i]+" ");
}