p1oXYZ
p1oXYZ

Reputation: 84

How to replace char two times in C#?

I have a string "%hello%" and i want to get output "{hello}". I tried all my ideas but not working or not compiling. I added now compile error, i know the problem is in array index. It's my code:


char[] charArr = vars.xyz.ToCharArray();
StringBuilder asda = new StringBuilder(vars.xyz);
foreach (char ch in charArr)
{
    vars.count++;
    vars.charArrayCounter++;
    if (ch.Equals('%'))
    {
        vars.charCounter++;
    }
    switch (vars.charCounter)
    {
        case 1:
            asda[vars.charArrayCounter - 1] = '{';
            break;
        case 2:
            asda[vars.charArrayCounter - 1] = '{';
            vars.charCounter = 0;
            break;
    }
}

I get compile error:

System.ArgumentOutOfRangeException: „Index was out of range. Must be non-negative and less than the size of the collection.

In line: asda[vars.charArrayCounter - 1] = '{';

Upvotes: 1

Views: 108

Answers (2)

Lucero
Lucero

Reputation: 60190

var asda = System.Text.RegularExpressions.Regex.Replace(vars.xyz, @"%([^%]+)%", "{$1}");

Upvotes: 3

rene
rene

Reputation: 42443

Your juggling with indexes is error prone, specially if you have those as global state.

If I keep close to what you have now I suggest building up the StringBuilder by appending a char one by one and keep state to know if you encounteres a % character so you know what you need to append instead. That solves the Index out of range exeception by simply omitting index operations from the loop.

If I assume your vars is simlar to this:

static class vars
{
  public static string xyz ="%hello%"; 
}

That code could look like this:

char[] charArr = vars.xyz.ToCharArray();
StringBuilder asda = new StringBuilder();
var state = 0; // counter for 1st or 2nd replace
foreach (char ch in charArr)
{
    if (ch.Equals('%'))
    {
        switch(state)
        {
            case 0: // first
                asda.Append('{');     
            break;
            case 1: //second
                asda.Append('}');     
            break;
            default:
                // error? because we have now found 3 % chars
            break;
        }
        state++; // counter goes up
    } else {
      asda.Append(ch);  // add to the stringbuilder
    }
}

and that outputs {hello} in my testing. It will produce for %hel%lo% the result {hel}lo% but you can know something was off because state will be > 1.

The much shorter alternative (which opens new error cases) but omits any loops, leverages the IndexOf and LastIndexOf methods of the String class

StringBuilder asda2 = new StringBuilder(vars.xyz);
asda2[vars.xyz.IndexOf('%')]='{';
asda2[vars.xyz.LastIndexOf('%')]='}';

This has the benfit it will for the input %hel%lo% the result {hel%lo} which is maybe preferble. Do check if the input as a % at all, or it fail. I leave that for others to solve.

Upvotes: 2

Related Questions