Joe King Joe King - 11 months ago 48
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:


How would I go about deleting everything on each line after

Answer Source

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",
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)