【发布时间】:2012-01-18 11:38:18
【问题描述】:
我有一个字符串列表。他们看起来像:
this.is.the.first.one
that.is.the.second
thishasnopoint
有的有积分,有的没有积分。我只需要使用 c# 在可能的第一个点之前从其第一个字母截断字符串。截断的字符串应如下所示:
this
that
thishasnopoint
Google 搜索没有显示任何有用的线索。
【问题讨论】:
我有一个字符串列表。他们看起来像:
this.is.the.first.one
that.is.the.second
thishasnopoint
有的有积分,有的没有积分。我只需要使用 c# 在可能的第一个点之前从其第一个字母截断字符串。截断的字符串应如下所示:
this
that
thishasnopoint
Google 搜索没有显示任何有用的线索。
【问题讨论】:
简单的方法是这样的:
string firstBit = wholeString.Split('.')[0];
Split 将其转换为字符串数组,以'.' 字符分隔。对于thishasnopoint,数组只有一个元素。
【讨论】:
现在我理解正确了,字符串只是其中一个序列...所以可以这样做:
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<string> 带有三个字符串 - this that thishasnopoint
【讨论】:
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();
}
}
比“拆分”方法更快,但更复杂。
【讨论】: