如何在Java中交换字符串的第一个和最后一个字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1028095/
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
How can I exchange the first and last characters of a string in Java?
提问by
I am practicing over the summer to try and get better and I am a little stuck on the following:
我整个夏天都在练习以尝试变得更好,但我在以下方面有些困难:
http://www.javabat.com/prob/p123384
http://www.javabat.com/prob/p123384
Given a string, return a new string where the first and last chars have been exchanged.
给定一个字符串,返回一个新字符串,其中第一个和最后一个字符已被交换。
Examples:
例子:
frontBack("code") → "eodc"
frontBack("a") → "a"
frontBack("ab") → "ba"
Code:
代码:
public String frontBack(String str)
{
String aString = "";
if (str.length() == 0){
return "";
}
char beginning = str.charAt(0);
char end = str.charAt(str.length() - 1);
str.replace(beginning, end);
str.replace(end, beginning);
return str;
}
采纳答案by coobird
Rather than using the String.replace
method, I'd suggest using the String.substring
method to get the characters excluding the first and last letter, then concatenating the beginning
and end
characters.
String.replace
我建议使用该String.substring
方法获取不包括第一个和最后一个字母的字符,然后连接beginning
和end
字符,而不是使用该方法。
Furthermore, the String.replace
method will replace all occurrences of the specified character, and returns a new String
with the said replacements. Since the return is not picked up in the code above, the String.replace
calls really don't do much here.
此外,该String.replace
方法将替换所有出现的指定字符,并返回一个String
具有所述替换的新字符。由于没有在上面的代码中提取返回值,因此String.replace
调用在这里实际上并没有多大作用。
This is because String
in Java is immutable, therefore, the replace
method cannot make any changes to the original String
, which is the str
variable in this case.
这是因为String
在 Java 中是不可变的,因此,该replace
方法不能对原始 进行任何更改String
,str
在这种情况下是变量。
Also to add, this approach won't work well with String
s that have a length of 1. Using the approach above, a call to String.substring
with the source String
having a length of 1 will cause a StringIndexOutOfBoundsException
, so that will also have to be taken care of as a special case, if the above approach is taken.
另外要补充的是,这种方法不适String
用于长度为 1 的 s。使用上述方法,使用长度为 1String.substring
的源调用 sString
将导致 a StringIndexOutOfBoundsException
,因此也必须注意作为一种特殊情况,如果采用上述方法。
Frankly, the approach presented in indyK1ng's answer, where the char[]
is obtained from the String
and performing a simple swap of the beginning and end characters, then making a String
from the modified char[]
is starting to sound much more pleasant.
坦率地说,indyK1ng's answer 中提出的方法,其中char[]
是从 获得String
并执行开始和结束字符的简单交换,然后String
从修改后的字符char[]
开始听起来更令人愉快。
回答by mnuzzo
Strings can be split into an array of chars and can be made with an array of chars. For more details on String objects, go to the Java APIand click on String in the lower left pane. That pane is sorted alphabetically.
字符串可以拆分为一个字符数组,并且可以用一个字符数组组成。有关 String 对象的更多详细信息,请转到Java API并单击左下方窗格中的 String。该窗格按字母顺序排序。
Edit: Since some people are being more thorough, I think I'll give additional details. Create a char array using String's .toCharArray() method. Take the first element and store it in a char, swap the first element with the last, and place the element you stored in a char into the last element into the array, then say:
编辑:由于有些人更彻底,我想我会提供更多细节。使用 String 的 .toCharArray() 方法创建一个字符数组。取第一个元素并将其存储在一个字符中,将第一个元素与最后一个元素交换,并将您存储在一个字符中的元素放入数组的最后一个元素中,然后说:
String temp = new String(charArray);
and return that. This is assuming that charArray is your array of chars.
并返回。这是假设 charArray 是您的字符数组。
回答by John Kugelman
A couple of hints:
几个提示:
Strings are immutable, meaning they cannot be changed. Hence,
str.replace()
does not changestr
, instead it returns a new string.Maybe
replace
isn't the best... ConsiderfrontBack("abcabc")
: your function, if it were corrected, would replace'a'
with'c'
yielding"cbccbc"
, then'c'
with'a'
yielding"abaaba"
. That's not quite right!
字符串是不可变的,这意味着它们不能被改变。因此,
str.replace()
不会改变str
,而是返回一个新字符串。也许
replace
不是最好的......考虑frontBack("abcabc")
:你的功能,如果被纠正,将替换'a'
为'c'
yielding"cbccbc"
,然后替换'c'
为'a'
yielding"abaaba"
。这不太对!
回答by erickson
String
instances in Java are immutable. This means that you cannot change the characters in a String
; a different sequence of characters requires a new object. So, when you use the replace
method, throw away the original string, and use the result of the method instead.
String
Java 中的实例是不可变的。这意味着您不能更改String
; 中的字符。不同的字符序列需要一个新对象。因此,当您使用该replace
方法时,请丢弃原始字符串,并使用该方法的结果。
For this method, however, you probably want to convert the String
instance to an array of characters (char[]
), which are mutable. After swappingthe desired characters, create a new String
instance with that array.
但是,对于此方法,您可能希望将String
实例转换char[]
为可变的字符数组 ( )。后交换所需的字符,创建一个新的String
与该阵列的实例。
回答by FreeMemory
The replace
method in String
actually returns a String
, so if you were to insist on using replace
, you'd do:
中的replace
方法String
实际上返回 a String
,所以如果你坚持使用replace
,你会这样做:
beginReplace = str.replace( beginning, end );
endReplace = beginReplace.replace( end, beginning );
return( str );
But this actually doesn't solve your specificproblem, because replace
replaces all occurencesof a character in the string with its replacement.
但这实际上并不能解决您的具体问题,因为replace
将字符串中所有出现的字符替换为它的替换。
For example, if my string was "apple" and I said "apple".replace( 'p', 'q' ), the resulting string would be "aqqle."
例如,如果我的字符串是“apple”并且我说“apple”.replace( 'p', 'q' ),则结果字符串将是“aqqle”。
回答by Daniel Brückner
public String frontBack(String input)
{
return
input.substring(input.length() - 1) + // The last character
input.substring(1, input.length() - 1) + // plus the middle part
input.substring(0, 1); // plus the first character.
}
回答by akarnokd
Yet another example without creating additional objects:
另一个没有创建额外对象的例子:
if (str.length() > 1) {
char[] chars = str.toCharArray();
// replace with swap()
char first = chars[0];
chars[0] = chars[chars.length - 1];
chars[chars.length - 1] = first;
str = new String(chars);
}
return str;
Edit:Performing the swap on length = 1 string is no-op.
编辑:在 length = 1 字符串上执行交换是无操作的。
Edit 2:dfa's change to copyValueOf did not make any sense as the Java source says in String.java: "// All public String constructors now copy the data." and the call is just delegated to a string constructor.
编辑 2:dfa 对 copyValueOf 的更改没有任何意义,因为 Java 源代码在 String.java 中说:“// 所有公共字符串构造函数现在都复制数据。” 并且调用只是委托给一个字符串构造函数。
回答by user85421
You can use a StringBuilder that represents "a mutable sequence of characters".
It has all methods needed to solve the problem: charAt, setCharAt, length and toString.
您可以使用表示“可变字符序列”的 StringBuilder。
它具有解决问题所需的所有方法:charAt、setCharAt、length 和 toString。
回答by Thorbj?rn Ravn Andersen
if (s.length < 2) {
return s;
}
return s.subString(s.length - 1) + s.subString(1, s.length - 2) + s.subString(0, 1);
(untested, indexes may be of by one...
(未经测试,索引可能是一...
回答by Carl Manaster
Just another, slightly different, approach, so you get a sense of the spectrum of possibilities. I commend your attention to the quick exit for short strings (instead of nesting the more-complicated processing in an if() clause), and to the use of String.format(), because it's a handy technique to have in your toolbox, not because it's notably better than regular "+" concatenation in this particular example.
只是另一种略有不同的方法,因此您可以了解各种可能性。我建议您注意短字符串的快速退出(而不是将更复杂的处理嵌套在 if() 子句中)以及 String.format() 的使用,因为它是您工具箱中的一种方便技术,不是因为在这个特定示例中它明显优于常规的“+”连接。
public static String exchange(String s) {
int n = s.length();
if (n < 2)
return s;
return String.format("%s%s%s", s.charAt(n - 1), s.substring(1, n - 1), s.charAt(0));
}