在C#console app中,如何将拆分字符串的第一个数字放入二维数组?
string[,] table3x3 = new string[3, 3];
string myString = "11A23A4A5A87A5";
string[] splitA = myString.Split(new char[] { 'A' });
假设我有3x3的二维数组和一个带数字和元音的字符串。我拆分它们以便我可以将它们放在2Darray中。我应该包括什么样的循环,以便输出
Console.WriteLine(table3x3[0, 0]); //output: blank
Console.WriteLine(table3x3[0, 1]); //output: blank
Console.WriteLine(table3x3[0, 2]); //output: 2
Console.WriteLine(table3x3[1, 0]); //output: blank
Console.WriteLine(table3x3[1, 1]); //output: 4
Console.WriteLine(table3x3[1, 2]); //output: 5
Console.WriteLine(table3x3[2, 0]); //output: 8
Console.WriteLine(table3x3[2, 1]); //output: blank
Console.WriteLine(table3x3[2, 2]); //output: 5
从视觉上看,输出结果如下:
[ ][ ][2]
[ ][4][5]
[8][ ][5]
字符串中有9个数字和5个元音。它根据序列将分裂字符串的第一个数字返回到特定的2Darray中。
答案 0 :(得分:2)
这应该这样做:
string[,] table3x3 = new string[3, 3];
string myString = "11A23A4A5A87A5";
int stringIndex = -1;
bool immediatelyFollowsA = false;
for (int row = 0; row < 3; row++)
for (int col = 0; col < 3; col++)
{
while (myString[++stringIndex] == 'A')
{
immediatelyFollowsA = true;
}
if (immediatelyFollowsA)
{
table3x3[row,col] = myString[stringIndex].ToString();
immediatelyFollowsA = false;
}
}
或者,添加到原始起点:
string[,] table3x3 = new string[3, 3];
string myString = "11A23A4A5A87A5";
string[] splitA = myString.Split(new char[] { 'A' });
int index = 0;
bool first = true;
foreach (string part in splitA)
{
int row = index / 3;
int col = index % 3;
if (!first)
{
table3x3[row, col] = part[0].ToString();
}
index += part.Length;
first = false;
}