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

发布于 2024-10-30 08:53:39 字数 481 浏览 2 评论 0原文

我正在构建一个需要处理 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 并将结果添加到数组中,但我似乎无法让它工作。

I'm building an application that needs to deal with twitter messages. I have need of a functionality that cuts a string up at 30 characters, if the character at the 30 index isn't a space it will count back till it finds a space and add a \n to it so that it displays as multi line in my application.

I've tried several approaches but my knowledge of C# isn't that amazing yet. I got something basic going.

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

I figured i'd use Split and add the result to an array, but i can't seem to get it working.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

风情万种。 2024-11-06 08:53:39

更好的方法可能是用空格分割并重建少于 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;
    }
}

A better approach may be to split by spaces and reconstruct for the array lines that are shorter than 30 characters.

Here is an outline of how I would do this (untested):

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;
    }
}
乖乖兔^ω^ 2024-11-06 08:53:39

我将使用正则表达式来确定空白块的最后位置,以及后面的第一个非空白字符的位置。

I would use regular expressions to determine the last position of whitespace block, as well as the position of first non-whitespace character that follows.

悲喜皆因你 2024-11-06 08:53:39

感谢奥德的回答。

我从 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;
    }

Thanks Oded for your answer.

I started with Oded answer and then made it into a reusable functions.

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

Here is my unit test for the function.

        [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;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文