在较小的块中剪切较长的单词/字符串以适合字段

时间:2017-06-07 11:32:51

标签: c# string word-wrap

我想用一串多个单词填充一个字段。当我有大量的话语时,我需要分开这个词。如果我的单词超过10个字母,我需要在这个单词的第5位留一个空格。

如何使用较短的单词获取新的“myString”?

    static void Main(string[] args)
    {
        var myString = "This is my string with some loooooooooooooong words. Please devide meeeeeeeeeeeeeeeeeeeeeeeee";
        var myStringSplit = myString.Split();
        var query = myStringSplit.Where(x => x.Length > 10).ToList();
        foreach (var item in query)
        {
            item.Insert(5, " ");
        }
    }

修改:我的预期结果:myString = "This is my strin g with some loooo ooooo ooooo ng words. Pleas e devid e meeee eeeee eeeee eeeee eeeee e";

3 个答案:

答案 0 :(得分:2)

以下是如何获得结果的示例:

public static void Main(string[] args)
{
    var myString = "This is my string with some loooooooooooooong words. Please devide meeeeeeeeeeeeeeeeeeeeeeeee";
    string[] myStringSplit = myString.Split();
    for (int i =0;i<myStringSplit.Length;i++)
    {
        if(myStringSplit[i].Length>5)
            myStringSplit[i] = Regex.Replace(myStringSplit[i], ".{5}(?=.)", "$0 ");
    }
    var resultString = myStringSplit.Aggregate((x,y)=> x+" "+y);
    Console.WriteLine(resultString);
}

输出如下:

  

这是我用一些loooo ooooo ooooo ng words的话语。请   dev e e meeee eeeee eeeee eeeee eeeee e

答案 1 :(得分:0)

尝试这可能会有所帮助

static void Main(string[] args)
        {
            var myString = "This is my string with some loooooooooooooong words. Please devide meeeeeeeeeeeeeeeeeeeeeeeee";
            var myStringSplit = myString.Split();
            var query = myStringSplit.Where(x => x.Length > 10).ToList();
            foreach (var item in query)
            {
                string outString = Regex.Replace(item, ".{5}", "$0 ");
            }
        }

这将在每五个单词后分隔字符串..

<强>被修改

答案 2 :(得分:0)

static void Main(string[] args)
{
    var myString = "This is my string with some loooooooooooooong words. Please devide meeeeeeeeeeeeeeeeeeeeeeeee";
    var newString = string.Empty;
    var myStringSplit = myString.Split();
    var query = myStringSplit.Where(x => x.Length > 10).ToList();
    foreach (var item in myStringSplit)
    {
        if(item.Length > 10)
        {
            var itemToSplit = item;
            itemToSplit.Insert(5, " ");
            newString += itemToSplit;
        }
        else
        {
           newString += item;
        }
    }
}

它应该是这样的。您尝试不起作用的原因是因为您不允许在foreach循环中编辑该项目。 More info on the foreach loop