Home > Software engineering >  How to change multiple char in string in c# .net
How to change multiple char in string in c# .net

Time:11-22

i want to replace string like :

CD7849O => CD18490

so if you find a char in the form of 7 and O, replace them with 1 and 0 (7 => 1, O => 0)

i tried with indexofchar but it's not work

string result = "CD7849O";

string[] charToFind = { "0", "O", "I", "1", "7" };
foreach (string z in charToFind)
{
    string charFind = z;
    int indexOfChar = result.Trim().IndexOf(charFind);
    Console.WriteLine(indexOfChar);

    if (indexOfChar >= 0)
    {
        string y = "XXX";
        string x = "XXX";

       
        if (z == "0" && z == "1")
        {
            y = "O";
            x = "I";
        }
        else if (z == "O" && z == "I")
        {
            y = "0";
            x = "1";
        }
        else if (z == "O" && z == "7")
        {
            y = "0";
            x = "1";
        }

        string resultY = result.Trim().Replace(charFind, y);
        string resultHasil;
        Console.WriteLine(resultY);
    }
}

CodePudding user response:

Use String.Replace()

string result = "CD7849O";
// replace 7 -> 1
result = result.Replace("7", "1");
// replace O -> 0
result = result.Replace("O", "0");

CodePudding user response:

Replace method will replace the char if it's found e.g. result = result.Replace("7", "1");. If you still want to check whether the char is present then you use the IndexOf method. it will return -1 if the char is not found else will return the index of the first char it finds. you can add a check if index > -1

  • Related