Home > Software design >  How to replace specific character of the string number of time
How to replace specific character of the string number of time

Time:07-31

I have following string string str = "HELLO BONUS USER . BYE LOWER";

based on number I need to replace its value with empty. for example,

int B = 1, L = 2;

I need to remove B from the string one time and, L from the string two times. how can I do it?

expected output: HEO ONUS USER . BYE LOWER.

I tried this, simple C# replace, but problem is its replace all the characters.

 var value = str.Replace("L", "");

CodePudding user response:

You can achieve it using Regex. See below code which defines an extension method to replace a char n times.

public static class StringExtensions
{
    public static string ReplaceChar(this string s, char c, int times)
    {
        var regex = new Regex(Regex.Escape(c.ToString()));
        return regex.Replace(s, string.Empty, times);
    }
}

Usage :

var newText = "HELLO BONUS USER . BYE LOWER".ReplaceChar('B', 1);       
newText = newText.ReplaceChar('L', 2);
Console.WriteLine(newText);

The above will print the output as

HEO ONUS USER . BYE LOWER

Check the execution and output at this fiddle.

CodePudding user response:

no method for this function, you can use substring. use in loop for number of char

    for(int i=0;i<L;i  )
    {
      var res = str.Substring(0,str.IndexOf('L')) str.Substring(str.IndexOf('L') 1);
    }

CodePudding user response:

Have a go with zero-width lookbehinds:

int B = 1, L = 2;
string str = "HELLO BONUS USER . BYE LOWER";
var res = Regex.Replace(str, "(?:(?<!(?:B[^B]*){" B "})B|(?<!(?:L[^L]*){" L "})L)", "");
Console.WriteLine(res);

Writes:

HEO ONUS USER . BYE OWER

CodePudding user response:

I know you tagged regex, but you can also code it explicitly. For example:

static string SkipTimesStr(this string source, char value, int times)
    => string.Concat(source.SkipTimes(value, times));   

static IEnumerable<T> SkipTimes<T>(this IEnumerable<T> source, T value, int times)
{
    foreach (var t in source)
    {
        if (times > 0 && EqualityComparer<T>.Default.Equals(t, value))
        {
            times--;
            continue;
        }
        yield return t;
    }
}

Then use like:

var result = "HELLO BONUS USER . BYE LOWER".SkipTimesStr('B', 1).SkipTimesStr('L', 2);

CodePudding user response:

Another way is by using a dictionary, the key (char type) is the removal of letters and the value (int type) is the time we need to remove the letters. By iterating through the string characters, we can maintain our dictionary values to let only allowed letters be included.

string str = "HELLO BONUS USER . BYE LOWER";
var letterRemovalByTimes = new Dictionary<char, int>
{
    { char.Parse("B"), 1 },
    { char.Parse("L"), 2 }
};
StringBuilder sb = new StringBuilder();

foreach (var t in str)
{
    letterRemovalByTimes.TryGetValue(t, out int v);
    if (letterRemovalByTimes.ContainsKey(t) && v > 0)
    {
        letterRemovalByTimes[t] -= 1;
    }
    else
    {
        sb.Append(t);
    }
}

Console.WriteLine(sb);

Output

HEO ONUS USER . BYE LOWER

note: thanks to Jeppe Stig Nielsen for pointing using char instead of a string.

  • Related