Joe King Joe King - 1 month ago 6
C# Question

C# How to delete every character after something on every line

So I've been trying to figure out how to delete characters after a certain point on each line, for example I have a list like:

dskfokes=dasfn3rewk
dsanfiwen=434efsde
damkw4343=o3rm3i
dmfkim303rk2=0439wefksd
32i32j9esfj=42393jdsf


How would I go about deleting everything on each line after
'='
?

Answer

I suggest you to use a combination of string handling operations SubString and IndexOf to achieve this, consider the example:

List<string> inputLine = new List<string>(){ "dskfokes=dasfn3rewk",
                                          "dsanfiwen=434efsde",
                                          "damkw4343=o3rm3i",
                                          "dmfkim303rk2=0439wefksd",
                                          "32i32j9esfj=42393jdsf"};
List<string> outputLines = inputLine.Select(x => 
                           x.IndexOf('=') == -1 ? x :
                           x.Substring(0, x.IndexOf('='))).ToList();

Note : The IndexOf will return -1 if the specified index was not found, in such cases substring method will throws errors since -1 will not be a valid index. So we have to check for existence of index withing the string before proceeding. you can also try simple foreach as like this:

List<string> outputLines=new List<string>();
int currentCharIndex=-1;
foreach (string line in inputLine)
{
    currentCharIndex = line.IndexOf('=');
    if(currentCharIndex ==-1)
        outputLines.Add(line);
    else
        outputLines.Add(line.Substring(0,currentCharIndex));
}
Comments