我想交换字符串的每第二个字符。

huangapple go评论76阅读模式
英文:

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 = &quot;welcome&quot;;
StringBuilder sb = new StringBuilder();
for (int i = 0; i &lt; s.length(); i += 2) {
	if (i + 1 &lt; 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&lt;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(&quot;welcome&quot;);
}

huangapple
  • 本文由 发表于 2020年9月21日 10:37:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63985512.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定