在 C# 控制台应用程序中,如何将分割字符串的第一个数字放入二维数组中?
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 个元音。它根据序列将分割字符串的第一个数字返回到特定的二维数组中。
最佳答案
这应该可以做到:
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;
}
关于c# - 将分割字符串的第一个数字放入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10858535/