如何在C#中将字符串拆分为行 [英] How Can I Split String Into Line In C#

查看:703
本文介绍了如何在C#中将字符串拆分为行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个刺痛



string = abc 10 20 10 10 10 pqr 10 20 10 10 10 wer 10 10 10 10 10 tryfhh 20 20 30 30 30



我怎么能分成一行

abc 10 20 10 10 10

pqr 10 20 10 10 10

wer 10 10 10 10 10

tryfhh 20 20 30 30 30

I have one sting

string = abc 10 20 10 10 10 pqr 10 20 10 10 10 wer 10 10 10 10 10 tryfhh 20 20 30 30 30

how can i split into line as a
abc 10 20 10 10 10
pqr 10 20 10 10 10
wer 10 10 10 10 10
tryfhh 20 20 30 30 30

推荐答案

这个怎么样?



How about this?

string source = "abc 10 20 10 10 10 pqr 10 20 10 10 10 wer 10 10 10 10 10 tryfhh 20 20 30 30 30";
string regExp = "[a-z]+";
Regex regx = new Regex(regExp);
MatchCollection collection = Regex.Matches(source, regExp);
for (int index = 1; index < collection.Count; index++)
{
    source = source.Replace(collection[index].Value, System.Environment.NewLine + collection[index].Value);
}
Console.WriteLine(source);


....或者使用int.TryParse作为测试继续的另一种方法当前行。





.... or another approach using int.TryParse as the test to continue the current line.


string sOutput = string.Empty;
string sInput = "abc 10 20 10 10 10 pqr 10 20 10 10 10 wer 10 10 10 10 10 tryfhh 20 20 30 30 30";
string[] sStringArray = sInput.Split(' ');
StringBuilder sb = new StringBuilder();
int iTmp = int.MinValue;

for(int i = 0; i<sStringArray.length;i++){
    if (int.TryParse(sStringArray[i], out iTmp))
    {
        //If the current array value is a number, then continue the current line ....
        sb.Append(sStringArray[i]);
        sb.Append(" ");
    }
    else
    {
        //Current array value is not a number
        if (i == 0)
        {
            // on the 1st iteration, we don't need a new line before the text value ...
            sb.Append(sStringArray[i]);
        }
        else
        {
            // on subsequent iterations, we need a new line before the text value ...
            sb.Append(Environment.NewLine);
            sb.Append(sStringArray[i]);
            sb.Append(" ");
        }
    }
}
sOutput = sb.ToString();
sb = null;







希望有所帮助。




Hope it helps.


你可以使用IndexOf。



you can use IndexOf.

int index = myString.IndexOf(' ');
int count=0;
while (index >= 0)
{
if (count == 5)
{
// take a substring of the string using index value and store it as you want
count=0;

}
    count++;
    index  = myString.IndexOf(' ', index + 1);
}


这篇关于如何在C#中将字符串拆分为行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆