首页 > 解决方案 > 在c#中转到子字符串的末尾

问题描述

注释 // 到结尾,我不知道如何干净地结束子字符串 :( 有没有更简单的方法可以走到子字符串的末尾而不是自己算出数字?对于更复杂的字符串,这将太难了

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

            }

我不知道stackoverflow想要什么更多的细节,任何能回答这个问题的人都可以清楚地理解这个简单的代码。

标签: c#stringsubstring

解决方案


您可以使用String.Substring(int)重载,它会自动继续到源字符串的末尾:

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

从此实例中检索子字符串。子字符串从指定的字符位置开始,一直持续到字符串的末尾。


推荐阅读