日期:2014-05-19  浏览次数:20940 次

C#字符串循环取值放到字符串数组中,急等,急,急
我想把str中的线路1,线路2……放到stringIn数组中,写的代码如下:运行结果总是显示,在stringIn中总是先显示8个线路0,先把8个线路0刷新成个线路1……
想请问这个循环如何写,谢谢了。

str= "线路0线路1线路2线路3线路4线路5线路6线路7 ";
string[]   stringIn=new   string[8];
for(int   x0=0;x0 <str.Length;x0=x0+3)
        for(int   a=0;a <8;a++)
{
          stringIn[a]=str.Substring(x0,3);
}

------解决方案--------------------
string str = "线路0线路1线路2线路3线路4线路5线路6线路7 ";
string[] stringIn = new string[8];
for (int i = 0; i < str.Length / 3; i++)
{
stringIn[i] = str.Substring(i * 3, 3);
}
------解决方案--------------------
string str = "线路0线路1线路2线路3线路4线路5线路6线路7 ";
string[] stringIn = new string[8];
for (int x0 = 0; x0 < str.Length; x0 = x0 + 3)
{
stringIn[x0/3] = str.Substring(x0, 3);
}

for (int i = 0; i < stringIn.Length; i++)
{
Console.WriteLine(stringIn[i]);
}

------解决方案--------------------
用正则:
string str = "线路0线路1线路2线路3线路4线路5线路6线路7 ";
System.Text.RegularExpressions.Regex regex = new Regex(@ "线路\d ");
System.Text.RegularExpressions.MatchCollection mc = regex.Matches(str);
string[] stringIn = new string[mc.Count];
for (int i = 0; i < stringIn.Length; i++)
{
stringIn[i] = mc[i].Value;
}
------解决方案--------------------
用正则:
string str = "线路0线路1线路2线路3线路4线路5线路6线路7 ";
System.Text.RegularExpressions.Regex regex = new Regex(@ "线路\d ");
System.Text.RegularExpressions.MatchCollection mc = regex.Matches(str);
string[] stringIn = new string[mc.Count];
for (int i = 0; i < stringIn.Length; i++)
{
stringIn[i] = mc[i].Value;
}
=======================》
正则可以,不过是不是应该是@ "线路\d+ "
------解决方案--------------------
这个比较容易理解
string str = "线路0线路1线路2线路3线路4线路5线路6线路7 ";
string[] stringIn = new string[8];
for (int i = 0; i < str.Length / 3; i++)
{
stringIn[i] = str.Substring(i * 3, 3);
}
------解决方案--------------------
以前没这么玩过,这样更简洁,的通用性更好一些

string str = "线路0线路1线路2线路3线路4线路5线路6线路7 ";
string[] stringIn = System.Text.RegularExpressions.Regex.Split(str, @ "(? <=\d)(?=线路) ");