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 回答