Search code examples
c#stringstringbuilder

StringBuilder specific case


I'm trying to delete certain char. and trim items in a list. Here is a simple illustration of my problem.

private void add_Click(object sender, EventArgs e)
{
    string[] s = { "Tarik \"F\"", "Tarik   ", "Tarik", "Souad  ", "Mehdi FARID", "Souad F  ", "DAFIR CCF", "khalid FA", "SAFAF" };

    char[] c = { 'F', ' ', '"' };
    foreach (string b in s)
    {
        txtDisplay.AppendText(b.TrimEnd(c) + "\n");
    }
}

the outcome is:

Tarik,
Tarik,
Tarik,
Souad,
Mehdi FARID,
Souad,
DAFIR CC: (for this item I want to keep the last 'F'),
SAFA    : (for this item I want to keep the last 'F')

The idea is, if the char 'F' is part of word it must not be deleted, if isolated then yes.


Solution

  • Use a regular expression:

            var regex = new Regex(@"\W+[Ff]*(?=\W|$)");
            foreach (var s in strings)
            {
                txtDisplay.AppendText(regex.Replace(s, "") + Environment.NewLine); 
            }
    

    This solution works no matter how many names the person has.