【问题标题】:Delete contents of a string including and after a specific word删除包含特定单词及其后的字符串内容
【发布时间】:2017-02-10 11:12:32
【问题描述】:

我需要取一个字符串,然后删除它的内容,包括指定短语和之后的内容,然后返回最后剩下的单词。 在这种情况下,“更多信息”。

基本上,这个脚本应该接受字符串

     "Please visit 

this 
website
 for more information if you have questions"

并返回单词"for"

(注意这只是一个例子,字符串可以是任何东西,我故意把它弄乱了换行符,因为它看起来有一半时间。)

下面的 split 方法有效,返回最后一个单词,但是 substring 方法无效。

知道我做错了什么吗?

   public static string InfoParse(string input)


{
    string extract = input;


    extract =  input.Substring(0, input.IndexOf("more information"));


    extract = extract.Split(' ').Last();

    return extract;



}

【问题讨论】:

    标签: c# substring


    【解决方案1】:

    改成这样:

        public static string InfoParse(string input)
        {
            //string extract = input;
            string extract = input.Substring(0, input.IndexOf("more information"));
            extract = extract.Split(new string[] {" ", "\r\n", "\r", "\n"}, StringSplitOptions.RemoveEmptyEntries).Last();
            return extract;
        }
    

    或者这个来显示你的代码有什么问题:

    public static string InfoParse(string input)
    {
        //string extract = input;
        string extract = input.Substring(0, input.IndexOf(" more information"));
        extract = extract.Split(' ').Last();
        return extract;
    }
    

    您的拆分返回条目 after 最后一个空格,最后一个空格恰好是“更多信息”之前的空格 --> 所以它返回一个空字符串

    编辑:现在也带有换行符

    【讨论】:

    • 第一个显然更健壮(考虑到他们“搞砸了换行符等”)最好不要指望一致的空白。
    • 没错,就是想展示原始Question-Source的确切问题
    • 它有效,但它正在考虑将换行符作为最后一个单词的一部分。为了解析最后一个单词,有没有办法让它将换行符视为空格?
    • 我已经编辑了我的答案,只使用第一种方法,现在应该也适用于换行符
    【解决方案2】:

    你可以使用正则表达式:

    using System.Text.RegularExpressions;
    
    string InfoParse(string input, string word)
    {
        Match m = Regex.Match(input, @"\s?(?<LastBefore>\w+)\s+" + word, RegexOptions.Singleline);
        if (m.Success)
            return m.Groups["LastBefore"].Value;
        return null;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-23
      • 1970-01-01
      • 2022-10-24
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-11
      相关资源
      最近更新 更多