开发者

How to double all the instances of character in a given string. using c#

For example, double all instances of 'X' in the string “ABCXYZ” will become “ABCXXYZ”

I am thinking of solving this way :

  1. copy the string to char array
  2. Go entire array and find out the # of occurances of the 'X' in the string
  3. find out the new length with # of occurances * 2
  4. Iterate the char arr开发者_运维技巧ay and store 'X' twice for each occurance of 'X'
  5. Copy back char array to string

Is there a efficient way to do this in c#, please suggest one

Thanks


The Replace method can do this:

"ABCXYZ".Replace("X","XX")

If you don't know what character in advance, you can do this using the string constructor:

string s = "ABCXYZ";
char c = 'X';
s = s.Replace(new string(c,1),new string(c,2))


OK, with your new requirement not to use ready-made string methods, how about:

var sbOut = new StringBuilder();
string myString = "ABCXYZ";
foreach (char c in myString) {
    sbOut.Append(c);
    if (c == 'X') {
        sbOut.Append(c);
    }
}
Console.WriteLine(sbOut.ToString());


String.Replace would give you the right string, I think, but it won't give you the number of replacements. To do that efficiently, maybe something like this:

char[] chars = string.ToCharArray();
char[] destchars = new char[chars.Length * 2]; // Max possible string size
int xidx = 0;

// Replace the X's
for(int i = 0; i < chars.Length; ++i)
{
   if(chars[i] == 'X')
   {
      destchars[xidx] = destchars[xidx + 1] = chars[i];
      xidx += 2;
   }
   else
      destchars[xidx++] = chars[i];
}

int numberOfXs = (xidx - chars.Length);
string newstr = new string(destchars, xidx);

I typed this in by hand and didn't run it or debug it, but you get the idea. It might be a bit memory heavy with the double-sized buffer in addition to the copies.


Just for fun and because you said you didn't want to use the built in string method to do it I wrote an extension method. I have no idea how efficient this really is. It should be fairly efficient but I make no guarantees.

public static class StringExt
{
    public static IEnumerable<char> DoubleChar(this IEnumerable<char> inString,
                                               char dupChar)
        {

         foreach (char c in inString)
         {
            yield return c;
            if (c == dupChar)
            {
                yield return c;
            }
         }
    }
}

You would then use it like this:

string x = new string("ABCXYZ".DoubleChar('X').ToArray());

This also allows you to chain together calls without having to do make multiple copies of your string. So you could do something like this:

string x = new string("ABCXYZ".DoubleChar('X').DoubleChar('Y').ToArray());
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜