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);