Home > Software design >  Text editing small program
Text editing small program

Time:11-24

The program should return edit text, where you have to replace" - ", ": ", "; ", ", ", " " with "\t".

The problem here is the result

Input: Китай: 1405023000; 24.08.2020; 17.99%

Expected    Китай   1405023000  24.08.2020  17.99%

Myne        Китай:  1405023000; 24.08.2020; 17.99%

So for some reason, I believe he messing with the order of `stringSeparators` elements or what. I am interested in this moment

public static string ReplaceIncorrectSeparators(string text)
{
    string populationEdited = "";
    string[] stringSeparators = new string[] {" - ", ": ", "; ", ", ", " "};
    for (int i = 0; i < stringSeparators.Length; i  )
    {
        populationEdited = text.Replace(stringSeparators[i], "\t");
    }

    return populationEdited;
}

I've already solved the problem in another way but I want to solve it with separators.

CodePudding user response:

The main problem in your code is that it doesn't store the result of Replace properly. This should do the trick:

public static string ReplaceIncorrectSeparators(string text)
{
    string populationEdited = text; // You need to start with the original
    string[] stringSeparators = new string[] {" - ", ": ", "; ", ", ", " "};
    for (int i = 0; i < stringSeparators.Length; i  )
    {
        // And here instead of text.Replace you do populationEdited.Replace
        populationEdited = populationEdited.Replace(stringSeparators[i], "\t");
    }

    return populationEdited;
}

CodePudding user response:

You could Regex as an alternative. It would make your code shorter (an in my opinion more readable).

public static string ReplaceIncorrectSeparators(string text)
{
    Regex regex = new Regex(@" - |: |; |, | ");
    return regex.Replace(text, "\t");
}
  • Related