Joe King
Joe King

Reputation: 13

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 '='?

Upvotes: 1

Views: 100

Answers (4)

sujith karivelil
sujith karivelil

Reputation: 29006

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));
}

Upvotes: -1

Mohit S
Mohit S

Reputation: 14044

You may also do it using String.Split() like

string[] allWords = new string[] {
"dskfokes=dasfn3rewk",
"dsanfiwen=434efsde",
"damkw4343=o3rm3i",
"dmfkim303rk2=0439wefksd",
"32i32j9esfj=42393jdsf"
};

foreach(string s in allWords)
{
    string[] urstring = s.Split('=');
    Console.WriteLine(urstring[0]);
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

One approach is to use LINQ:

var strings = new string[] {
    "dskfokes=dasfn3rewk
,   "dsanfiwen=434efsde
,   "damkw4343=o3rm3i
,   "dmfkim303rk2=0439wefksd
,   "32i32j9esfj=42393jdsf
};
var res = strings.Select(s => s.Split('=')[0]).ToArray();

This splits each string on =, and drops everything after the first '=' character if it is there.

Upvotes: 1

Ryan Hu
Ryan Hu

Reputation: 332

Use string.IndexOf() to get the index of the char you want to remove, then string.Remove() to do the removing.

string str = "dskfokes=dasfn3rewk";
str = str.Remove(str.IndexOf('='));

Upvotes: 4

Related Questions