Ways to break text after a certain number of words or characters in C#? [closed]

人走茶凉 提交于 2019-12-05 20:31:36
ChaseMedallion

4 words

As O. R. Mapper said in his comment, this really depends on your ability to define a "word" in a given string and what the delimiters are between words. However, assuming you can define the delimiter as whitespace, then this should work:

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 characters

string firstFortyCharacters = text.Substring(0, Math.Min(text.Length, 40));

Both

Combining both, we can get the shorter one:

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

Answer to your question #2: Place this in a static class and you get a nice extension method that inserts a string at given intervals in another string

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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!