【问题标题】:truncate string from the first letter before the first point?从第一个点之前的第一个字母截断字符串?
【发布时间】:2012-01-18 11:38:18
【问题描述】:

我有一个字符串列表。他们看起来像: this.is.the.first.one that.is.the.second thishasnopoint 有的有积分,有的没有积分。我只需要使用 c# 在可能的第一个点之前从其第一个字母截断字符串。截断的字符串应如下所示: this that thishasnopoint Google 搜索没有显示任何有用的线索。

【问题讨论】:

    标签: c# string truncate


    【解决方案1】:

    简单的方法是这样的:

    string firstBit = wholeString.Split('.')[0];
    

    Split 将其转换为字符串数组,以'.' 字符分隔。对于thishasnopoint,数组只有一个元素。

    【讨论】:

    • Slick...,对于那些没有句点的字符串,将始终在数组的零位置返回整行...酷...
    【解决方案2】:

    现在我理解正确了,字符串只是其中一个序列...所以可以这样做:

    var result = strings.Split('.').First();
    

    如果字符串是:this.is.the.first.one that.is.the.second thishasnopoint - 一个字符串:

    var firstWords = new List<string>();
    strings.Split(' ').ForEach(x => firstWords.Add(x.Split('.').First()));
    

    会返回:

    List&lt;string&gt; 带有三个字符串 - this that thishasnopoint

    【讨论】:

      【解决方案3】:
      string getTruncated(string s) {
          int startIdx = -1;
          for (int i = 0; i < s.Length; ++i) {
              if (Char.IsLetter(s[i])) {
                  startIdx = i;
                  break;
              }
          }
          int endIdx = s.IndexOf('.');
          if (startIdx != -1) {
              if (endIdx != -1) {
                  return s.Substring(startIdx, endIdx);
              } else {
                  return s.Substring(startIdx);
              }
          } else {
              throw new ArgumentException();
          }
      }
      

      比“拆分”方法更快,但更复杂。

      【讨论】:

      • 内部是如何实现拆分的?是什么让这更快?
      • 呃...为什么假设这是对性能敏感的?与使用 Split 的版本相比,您的代码的可维护性大大降低。此外,如果给您一个类似 111.234 的字符串,OP 不排除该字符串,您的代码将导致 ArgumentException。
      • Hammerstein,split 方法创建字符串数组,例如对于 input == "this.is.first.phrase",split('.') 将返回 String[] {"this", " is", "first", "phrase"} 数组,其中仅使用第零个元素,其他元素将被 GC。正如 post 的创建者所说,结果必须是第一个字母和第一个点之间的子字符串。然后如果输入只有数字,则抛出异常。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多