如何交换字符串中的字符 [英] how to swap characters in a string

查看:107
本文介绍了如何交换字符串中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好.
我是.Net的新手,我想学习.
我的问题是如何更改字符串中的字符.正在尝试在Google上找到解决方案,但我找不到它.
例如:如何在"badc"中更改字符串"abcd".

我可以交换前两个字符,但是我不知道如何更改其他字符.
我就是这样做的:

Hi all.
I''m new in .Net and i want to learn.
My question is how to change characters in string. Was trying to find solution on google, but i couldn''t find it.
For example: how to change string "abcd" in "badc".

I can swap first 2 characters, but i dont have idea how to change others.
This is how i done that:

static string Swap(string str, int index1, int index2)
        {
            char[] c = str.ToCharArray();
            char temp = c[index1];
            c[index1] = c[index2];
            c[index2] = temp;

            return new string(c);
        }


请有人帮我.
Thx.


Plz can someone help me.
Thx.

推荐答案

使用循环并找到奇数位置,并与一个递增的偶数位置交换,例如:1等于2,反之亦然3等于4,依此类推.使用与您编写的逻辑相同的逻辑,但是通过计算ur字符串的长度来应用循环.
Use Loop and find odd positions and swap with one incremented even position eg: 1 with 2 and vice versa 3 by 4 and so on. use the same logic which u have written but apply the loop by calculating the length of ur string.


请尝试以下代码.

Try as below code.

string input = "AXBYCZ";
StringBuilder output = new StringBuilder();

char[] characters = input.ToCharArray();
        
for (int i = 0; i < characters.Length; i++)
{
  if (i % 2 == 0)
  {
    if((i+1) < characters.Length )
    {
      output.Append(characters[i + 1]);
    }
               output.Append(characters[i]);
  }

}



输入:"AXBYCZ"
输出:"XAYBZC"

如果字符串的长度是奇数.然后最后一个字符将保持其原始位置.

输入:"AXBYCZT"
输出:"XAYBZCT"



Input: "AXBYCZ"
Output: "XAYBZC"

Incase length of string is odd number. Then last character will maintain its original position.

Input: "AXBYCZT"
Output: "XAYBZCT"


我发布了有关如何执行此操作的提示/技巧,但是该死的iPad正在截断该链接.除非其他人愿意张贴它,否则您将不得不在该网站上进行搜索(否则我会从我的差事中回家).

编辑=====================

用于反转字符串和StringBuilder对象的扩展方法 [ ^ ]
I posted a tip/trick about how to do this, but this damn iPad is truncating the link. You''re gonna have to search the site for it unless someone else is willing to post it (or I get home from my errands).

EDIT =======================

Extension Methods to Reverse a String and StringBuilder Object[^]


这篇关于如何交换字符串中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆