C#编辑一个字符串以添加一定长度的换行符

我正在构建一个需要处理Twitter消息的应用程序。我需要一个能够将字符串剪切为30个字符的功能,如果30索引处的字符不是空格,它将重新计算,直到找到空格并向其添加 n以使其显示为多行在我的申请中。 我已经尝试了几种方法,但我对C#的了解并不是那么神奇。我有一些基本的东西。
string[] stringParts = new string[5];
string temp = jsonData["results"][i]["text"].ToString();
int length = 30;

for(int count = length-1; count >= 0; count--)
{
    if(temp[count].Equals(" "))
    {
        Debug.Log(temp[count]);
    } 
}
我想我会使用Split并将结果添加到数组中,但我似乎无法使其正常工作。     
已邀请:
更好的方法可能是按空格分割并重建短于30个字符的数组行。 以下是我将如何做到这一点(未经测试):
string[] words = myString.Split(' ');
StringBuilder sb = new StringBuilder();
int currLength = 0;
foreach(string word in words)
{
    if(currLength + word.Length + 1 < 30) // +1 accounts for adding a space
    {
      sb.AppendFormat(" {0}", word);
      currLength = (sb.Length % 30);
    }
    else
    {
      sb.AppendFormat("{0}{1}", Environment.NewLine, word);
      currLength = 0;
    }
}
    
我将使用正则表达式来确定空白块的最后位置,以及后面的第一个非空白字符的位置。     
谢谢Oded的回答。 我从Oded回答开始,然后将其变成可重用的函数。
public string ShortenLineLengthForEachParagraph(string origMsg, int maxLineLength)
    {
        StringBuilder sb = new StringBuilder();
        string[] paragraphs = origMsg.Split(new string[] {Environment.NewLine}, StringSplitOptions.None);
        foreach (var paragraph in paragraphs)
        {
            sb.AppendLine(ShortenLineLength(paragraph,maxLineLength));
        }
        return sb.ToString();
    }

    private string ShortenLineLength(string origMsg, int maxLineLength)
    {
        StringBuilder sb = new StringBuilder();
        string[] words = origMsg.Split(' ');
        int currLineLength = 0;
        foreach (string word in words)
        {
            if (currLineLength + word.Length + 1 < maxLineLength) // +1 accounts for adding a space
            {
                if (currLineLength == 0)
                {
                    sb.Append(word);
                    currLineLength = currLineLength + word.Length;
                }
                else
                {
                    sb.AppendFormat(" {0}", word);
                    currLineLength = currLineLength + word.Length + 1; // +1 accounts for adding a space
                }

            }
            else
            {
                sb.AppendFormat("{0}{1}", Environment.NewLine, word);
                currLineLength = word.Length;
            }
        }
        return sb.ToString().TrimEnd(Environment.NewLine.ToCharArray());
    }
这是我对该功能的单元测试。
        [TestMethod()]
    public void ShortenLineLengthForEachParagraphTest()
    {
        int maxLength = 75;

        var sut = new Service();
        var shortenedLines = sut.ShortenLineLengthForEachParagraph(GetParagraphs(), maxLength);
        var lines = shortenedLines.Split(Environment.NewLine.ToCharArray());
        Assert.IsTrue(lines.All(x => x.Length < maxLength));
    }

    private string GetParagraphs()
    {
        var s = $@"Credibly syndicate alternative niches after technically sound internal or ""organic"" sources. Compellingly build go forward products with innovative process improvements. Dynamically monetize integrated quality vectors whereas alternative benefits. Seamlessly scale web-enabled niche markets after client-centered portals. Appropriately extend cross-media models after diverse users.

Globally supply client - centered mindshare through real - time infrastructures.Dynamically reintermediate frictionless growth strategies vis-a - vis high standards in products.Authoritatively formulate turnkey imperatives for go forward ideas.Professionally architect alternative products before 2.0 communities.Progressively incentivize standardized infrastructures vis - a - vis proactive technologies.

Continually revolutionize e - business strategic theme areas and strategic synergy.Compellingly enhance professional functionalities after customer directed metrics.Credibly streamline one - to - one deliverables after synergistic users.Distinctively morph user friendly metrics via performance based web - readiness.Rapidiously strategize premium supply chains after technically sound scenarios.

Synergistically simplify cross - media data after real - time communities.Authoritatively engineer customized collaboration and idea - sharing via plug - and - play intellectual capital.Progressively maintain cross - unit e - markets before resource maximizing ideas.Holisticly architect state of the art e - services for front - end vortals.Authoritatively extend professional value with open - source schemas.

             Dramatically architect enterprise paradigms vis - a - vis reliable functionalities.Globally engage tactical solutions after fully tested schemas.Globally predominate synergistic value whereas multidisciplinary synergy.Efficiently productize market positioning e - markets via user friendly total linkage.Intrinsicly promote cross - unit vortals rather than synergistic architectures.

             Dynamically optimize superior communities rather than B2B relationships.Collaboratively maintain competitive results with multidisciplinary growth strategies.Appropriately leverage other's accurate infrastructures without highly efficient growth strategies. Rapidiously synthesize user friendly resources without global deliverables. Holisticly harness cross-platform potentialities for web-enabled outsourcing.


             Phosfluorescently foster error - free models through open - source expertise.Progressively conceptualize impactful schemas before 24 / 365 web - readiness.Energistically underwhelm quality internal or ""organic"" sources rather than enterprise value.Compellingly scale one-to-one niche markets vis-a-vis long-term high-impact partnerships.Proactively exploit ethical expertise after technically sound benefits.

                  Assertively innovate enabled technologies with economically sound scenarios. Synergistically monetize an expanded array of process improvements before go forward channels. Completely strategize accurate action items without top-line technology. Rapidiously evisculate timely experiences through fully researched data. Distinctively fabricate low-risk high-yield innovation via real-time intellectual capital.

                  Conveniently coordinate plug-and-play quality vectors before ethical e-commerce.Continually supply market positioning networks through out-of-the-box internal or ""organic"" sources.Professionally myocardinate customized testing procedures whereas backward-compatible growth strategies.Dynamically maximize impactful methods of empowerment vis-a-vis error-free architectures.Monotonectally visualize orthogonal information and progressive meta-services.

               Intrinsicly matrix viral outsourcing before revolutionary opportunities.Collaboratively morph distributed services through backward-compatible value. Objectively integrate synergistic supply chains through distinctive ""outside the box"" thinking.Globally innovate e-business opportunities before market-driven human capital.Compellingly re-engineer market-driven niche markets through adaptive applications.


               Energistically implement standards compliant web-readiness vis-a-vis interactive resources.Rapidiously.";
        return s;
    }
    

要回复问题请先登录注册