4 个字
正如 OR Mapper 在他的评论中所说,这实际上取决于您在给定字符串中定义“单词”的能力以及单词之间的分隔符是什么。但是,假设您可以将分隔符定义为空格,那么这应该可以工作:
using System.Text.RegularExpressions;
string delimiterPattern = @"\s+"; // I'm using whitespace as a delimiter here
// find all spaces between words
MatchCollection matches = Regex.Matches(text, delimiterPattern);
// if we found at least 4 delimiters, cut off the string at the 4th (index = 3)
// delimiter. Else, just keep the original string
string firstFourWords = (matches.Count >= 4)
? (text.Substring(0, matches[3].Index))
: (text);
40 个字符
string firstFortyCharacters = text.Substring(0, Math.Min(text.Length, 40));
两个都
结合两者,我们可以得到更短的:
using System.Text.RegularExpressions;
string delimiterPattern = @"\s+"; // I'm using whitespace as a delimiter here
// find all spaces between words
MatchCollection matches = Regex.Matches(text, delimiterPattern);
// if we found at least 4 delimiters, cut off the string at the 4th (index = 3)
// delimiter. Else, just keep the original string
string firstFourWords = (matches.Count >= 4)
? (text.Substring(0, matches[3].Index))
: (text);
string firstFortyCharacters = text.Substring(0, Math.Min(text.Length, 40));
string result = (firstFourWords.Length > 40) ? (firstFortyCharacters) : (firstFourWords);