【问题标题】:splitting string at word - keep the left hand side在 word 处拆分字符串 - 保留左侧
【发布时间】:2023-03-24 01:42:02
【问题描述】:

我有字符串,在中间某处(左右长度不同)我有这个字符序列(左右都有一个空格)

到:

此时是否可以拆分并返回左侧的字符,即给定此字符串:

这里有一些文本:这里还有一些不同长度的文本

我想要的结果是:

这里有一些文字

【问题讨论】:

    标签: c# .net vb.net


    【解决方案1】:

    IndexOfSubstring 结合使用:

    string s = "Here is some text to: and here is some more text of a different length";
    
    int length = s.IndexOf("to:");
    
    if (length > 0)
    {
        s = s.Substring(0, length);
    }
    

    【讨论】:

      【解决方案2】:

      好吧,如果你知道你有那个词:

      String s = "Here is some text to: and here is some more text of a different length"
      String result = s.Split(new String[] { "to:" })[0];
      

      你拆分文本并取第一部分。

      如果您选择的子字符串不在字符串中,result 将只包含普通的s - 没有变化。

      【讨论】:

      • 1.已修复,谢谢! 2.如果to:不止一次出现,则只取第一部分。
      • 代码有效,但它遍历整个字符串,IMO 是不必要的。 .IndexOf & .SubString 性能更好。
      • @DannyChen 对此无可争辩,但Split 更简单,所以我觉得我也必须展示该解决方案。
      【解决方案3】:

      string.Split 更容易:

      Dim FirstSplit as String()
      FirstSplit = Name.Split(",")
      fname = FirstSplit(0).Trim()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-19
        • 2020-09-13
        • 1970-01-01
        • 1970-01-01
        • 2018-12-23
        • 1970-01-01
        相关资源
        最近更新 更多