英文:
I would like to swap every second character of a string
问题
我想交换字符串的每个第二个字符,像这样:
welcome -> ewclmoe
我该如何做到这一点?
英文:
I would like to swap every second character of a string like so:
welcome -> ewclmoe
How can I do this?
答案1
得分: 1
以下是翻译好的部分:
我更喜欢使用 StringBuilder
来构建输出。遍历原始 String
的偶数索引。首先附加下一个奇数字符(如果有的话),然后附加偶数字符。像这样:
String s = "welcome";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i += 2) {
if (i + 1 < s.length()) {
sb.append(s.charAt(i + 1));
}
sb.append(s.charAt(i));
}
System.out.println(sb);
输出结果(如所请求):
ewclmoe
英文:
I would prefer to build the output with a StringBuilder
. Iterate the even indices of the original String
. First append the next odd character (if there is one), then take the even character. Like,
String s = "welcome";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i += 2) {
if (i + 1 < s.length()) {
sb.append(s.charAt(i + 1));
}
sb.append(s.charAt(i));
}
System.out.println(sb);
Outputs (as requested)
ewclmoe
答案2
得分: 0
以下代码可以正常工作...
请查看...
public static void swapCharacter(String s) {
char[] a = s.toCharArray();
char temp;
for(int i=0; i<a.length-1; i+=2) {
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
System.out.println(new String(a));
}
public static void main(String[] args) {
swapCharacter("welcome");
}
英文:
below code works...
check it out...
public static void swapCharacter(String s) {
char[] a = s.toCharArray();
char temp;
for(int i=0; i<a.length-1;i+=2)
{
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
}
System.out.println(new String(a));
}
public static void main(String[] args) {
swapCharacter("welcome");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论