1

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);
    }
}
4
  • 3
    read up on String.Replace() Commented Nov 22, 2022 at 4:23
  • how do i find char 7 and O then replace with char 1 and 0 Commented Nov 22, 2022 at 4:29
  • @KikiOlivia Replace finds all instances of char in string and produces a new one with the replaced characters. Commented Nov 22, 2022 at 4:55
  • 1
    @KikiOlivia what is your goal and what is not working in the provided code? Commented Nov 22, 2022 at 4:55

2 Answers 2

1

Use String.Replace()

string result = "CD7849O";
// replace 7 -> 1
result = result.Replace("7", "1");
// replace O -> 0
result = result.Replace("O", "0");
Sign up to request clarification or add additional context in comments.

3 Comments

how do i find char 7 and O in string result ?, i know how to replace but I want to find if there are '7' and 'O' replace of '1' and '0'
@KikiOlivia, why are you specifying a requirement in a comment on an answer that you didn't specify in the question? Why would you think that it's a good idea to only provide half the relevant information in the question? Provide a FULL and CLEAR explanation in the question. That should be a given.
OP already uses Replace
1

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

1 Comment

OP already uses both methods in the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.