【问题标题】:Going to the end of a substring in c#在c#中转到子字符串的末尾
【发布时间】:2018-11-22 21:58:09
【问题描述】:

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

        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# string substring


【解决方案1】:

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

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

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

【讨论】:

  • 我之前试过这个,但没有注意到我最后忘记了一个“)”......谢谢
【解决方案2】:

在我看来,您只是想从加载的行中删除某个单词。如果这是您的任务,那么您可以简单地将单词替换为空字符串

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

或者甚至没有带有一点 Linq 的显式循环

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

或者,如果需要匹配单词后的附加字符,您可以使用正则表达式来解决。

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

【讨论】:

  • 必须将 word + 1 个字符替换为空
  • 我明白了,那么 Regex 可能会有所帮助。
  • 是的,我已经用 Regex 完成了这个,但想看看我是否可以不用它。谢谢
猜你喜欢
  • 2021-10-04
  • 2013-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-21
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
相关资源
最近更新 更多