Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#编辑字符串以添加特定长度的换行符_C#_String_Newline_Indexof_Splice - Fatal编程技术网

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

C#编辑字符串以添加特定长度的换行符,c#,string,newline,indexof,splice,C#,String,Newline,Indexof,Splice,我正在构建一个需要处理twitter消息的应用程序。我需要一种功能,可以将字符串切分为30个字符,如果30个索引处的字符不是空格,它将倒计时,直到找到空格并向其中添加一个\n,以便在我的应用程序中显示为多行 我尝试过几种方法,但我对C#的了解还没有那么惊人。我有一些基本的东西 string[] stringParts = new string[5]; string temp = jsonData["results"][i]["text"].ToString(); int length = 30;

我正在构建一个需要处理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=新的StringBuilder();
int currength=0;
foreach(单词中的字符串)
{
if(currength+word.Length+1<30)/+1用于添加空格
{
sb.AppendFormat(“{0}”,单词);
currength=(sb.Length%30);
}
其他的
{
sb.AppendFormat(“{0}{1}”,Environment.NewLine,word);
currength=0;
}
}

更好的方法可能是按空格分割,并为小于30个字符的数组行重建

以下是我将如何做到这一点的概要(未经测试):

string[]words=myString.Split(“”);
StringBuilder sb=新的StringBuilder();
int currength=0;
foreach(单词中的字符串)
{
if(currength+word.Length+1<30)/+1用于添加空格
{
sb.AppendFormat(“{0}”,单词);
currength=(sb.Length%30);
}
其他的
{
sb.AppendFormat(“{0}{1}”,Environment.NewLine,word);
currength=0;
}
}

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

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

感谢Oded的回答

我从Oded answer开始,然后将其制作成一个可重用的函数

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());
    }
public string shortenLineLengthForEach段落(string origMsg,int maxLineLength)
{
StringBuilder sb=新的StringBuilder();
string[]段落=origMsg.Split(新字符串[]{Environment.NewLine},StringSplitOptions.None);
foreach(段落中的var段落)
{
sb.附录(短长度(段落,最大长度));
}
使某人返回字符串();
}
专用字符串ShortenLineLength(字符串origMsg,int maxLineLength)
{
StringBuilder sb=新的StringBuilder();
string[]words=origMsg.Split(“”);
int currLineLength=0;
foreach(单词中的字符串)
{
if(currLineLength+word.Length+1
这是我对函数的单元测试

        [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;
    }
[TestMethod()]
public void ShortEnlineLengthForeach段落测试()
{
int maxLength=75;
var sut=新服务();
var shortenedLines=sut.shortenlinelengthforeachparagration(getparations(),maxLength);
var lines=shortenedLines.Split(Environment.NewLine.ToCharArray());
Assert.IsTrue(lines.All(x=>x.Length        [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;
    }