开发者

Replacing two characters with each other in a string, without using placeholder characters

I have this string

aabqqidjwljdpfjem

I need to replace b by p and p by b

aapqqidjwljdbfjem

the way I do this look like this

myvar.replace("b","1").replace("p","b").replace("1","p")

this is kind of really ugly开发者_运维百科

is there a better way?

edit

why ugly? because I have to decide/find an arbitrary set of characters that will work for any possible case


string sold = "aa**b**qqidjwljd**p**fjem";
string snew = Regex.Replace(sold, "(?<replace>b|p)", delegate(Match p)
{
    switch (p.Groups["replace"].Value)
    {
        case "b": return "p";
        case "p": return "b";
    };
    throw new ApplicationException("Should never happen!");
});


I think this should do it, i think it a lot more readable

      private static string Transpose(string s)
  {
     string output = "";
     foreach (char c in s)
     {

        switch (c)
        {
           case 'P':
              output += 'B';
              break;
           case 'B':
              output += 'P';
              break;
           default:
              output += c;
              break;
        }
     }
     return output;
  }

does not win any prizes for open closed principle though!


this seem to work too

var a = "aa**b**qqidjwljd**p**fjem";
a = new string((from n in a select (n == 'b' ? 'p' : (n == 'p' ? 'b' : n))).ToArray());


I can't think of a better way at the moment, really your method isn't that ugly.

Assuming that there is never a 1 in the string, it should work just fine.


Nope. It's the same as the standard swapping variables problem. (In order to swap the values of A and B, you need to use C).


Yours is as concise as I can think on a Friday afternoon. Depending on what Replace does internally, this might be quicker:

    char [] myChars = "aa**b**qqidjwljd**p**fjem".ToCharArray();

    for (int x = 0; x < myChars.Length; x++)
    {
        char currentCharacter = myChars[x];
        if (currentCharacter == 'b')
        {
            myChars[x] = 'p';
        }
        else if (currentCharacter == 'p')
        {
            myChars[x] = 'b';
        }
    }

    string myString = new string(myChars);


Your way works fine. The only problem would be is if there's ever a '1' in the string, as it will cause your logic to be corrupted.

A better solution would be to use a temporary character that you're sure will never appear in the text, like a pipe ('|') or a tilde ('~') for example.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜