删除特定单词或句子后的字符

时间:2019-04-22 07:39:53

标签: c# .net string substring

字符删除的工作原理如下:

input = input.Substring(0, input.IndexOf("/") + 1);

我想在单词或句子后删除

例如删除[logo]和[logo]之后的所有内容

   string input= "Test test test    Have a nice day,      [logo]<http://www.example.com/>    John Nash  Software Developer    Google" 

新输入必须是这样的:

string input= "Test test test    Have a nice day,"

谢谢

2 个答案:

答案 0 :(得分:0)

好吧,IndexOfLength,最后,Substring应该做到:

string input = "Test test test    Have a nice day,... ";
string search = "Have a nice day,";

input = input.Substring(0, input.IndexOf(search) + search.Length);

编辑:如果您使用电子邮件,则可能需要测试多个结尾:

  string[] finals = new string[] {
    "Have a nice day,",
    "Buy,",
    "yours,"
  };

  int bestIndex = -1;

  foreach (var fin in finals) {
    int index = input.IndexOf(fin);

    if (index >= 0) {
      index += fin.Length;

      if (index > bestIndex) 
        bestIndex = index;
    }
  }

  input = bestIndex < 0 ? input : input.Substring(0, bestIndex);

答案 1 :(得分:0)

  1. 获取输入单词的索引
  2. 从0到(1)的单词索引获取子串