S.Kikk
S.Kikk

Reputation: 3

Going to the end of a substring in c#

The comment // go to end, I can't figure out how to cleanly end the substring :( Is there a simpler way to go to the end of the substring rather than mathing out the number by myself? For more complex strings this would be too hard

        string word = Console.ReadLine();
        string[] lines = File.ReadAllLines(file);
        using (var far = File.CreateText(resultfile))
        {
            foreach (string line in lines)
            {
                StringBuilder NewL = new StringBuilder();
                int ind = line.IndexOf(word);
                if (ind >= 0)
                {
                    if (ind == 0)
                    {
                        NewL.Append(line.Substring(ind+ word.Length +1, // go to end);
                    }else{
                    NewL.Append(line.Substring(0, ind - 1));
                    NewL.Append(line.Substring(ind + word.Length + 1, // go to end));}
                    far.WriteLine(NewL);
                }
                else
                {
                    far.WriteLine(line);
                }

            }

I don't know what more details the stackoverflow wants, anyone who can answer this pretty sure can clearly understand this simple code anyways.

Upvotes: 0

Views: 249

Answers (2)

Steve
Steve

Reputation: 216273

It seems to me that you are just trying to remove a certain word from the loaded lines. If this is your task then you can simply replace the word with an empty string

foreach (string line in lines)
{
    string newLine = line.Replace(word, "");
    far.WriteLine(newLine);
}

Or even without an explicit loop with a bit of Linq

var result = lines.Select(x = x.Replace(word,""));
File.WriteAllLines("yourFile.txt", result);

Or, given the requirement to match an additional character after the word you can solve it with Regex.

Regex r = new Regex(word + ".");
var result = lines.Select(x => r.Replace(x, ""));
File.WriteAllLines("yourFile.txt", result);

Upvotes: 2

Douglas
Douglas

Reputation: 54877

You can use the String.Substring(int) overload, which automatically continues to the end of the source string:

NewL.Append(line.Substring(ind + word.Length + 1));

Retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.

Upvotes: 4

Related Questions