3

与えられた文字列

" Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut"、後でそれを壊します

  1. 4ワード
  2. 40文字

C# 4(Monoプラットフォームと互換性を持たせるために)の最大言語バージョンを使用します。


更新/編集:

正規表現の実装

広告#2-40文字後に分割(この要点を参照)

using System;
using System.Text.RegularExpressions;
Regex.Split(
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut"
, "(.{40})"
, RegexOptions.Multiline)
.Where(s => !string.IsNullOrEmpty(s))
.ToArray();

この投稿はコミュニティウィキとして機能します。

4

2 に答える 2

5

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);
于 2012-09-22T22:24:46.193 に答える
1

質問2への回答:これを静的クラスに配置すると、指定された間隔で別の文字列に文字列を挿入する優れた拡張メソッドが得られます

public static string InsertAtIntervals(this string s, int interval, string value)
{
    if (s == null || s.Length <= interval) {
        return s;
    }
    var sb = new StringBuilder(s);
    for (int i = interval * ((s.Length - 1) / interval); i > 0; i -= interval) {
        sb.Insert(i, value);
    }
    return sb.ToString();
}
于 2012-09-22T23:11:59.897 に答える