有没有办法将每 2 个字符存储在一个字符串中?
例如
1+2-3-2-3+
所以它将是“1+”、“2-”、“3-”、“2-”、“3+”作为单独的字符串或数组。
最简单的方法是使用循环遍历字符串,并从当前位置获取两个字符的子字符串:
var res = new List<string>();
for (int i = 0 ; i < str.Length ; i += 2)
res.Add(str.Substring(i, 2));
高级解决方案可以使用 LINQ 做同样的事情,并避免显式循环:
var res = Enumerable
.Range(0, str.Length/2)
.Select(i => str.Substring(2*i, 2))
.ToList();
第二种解决方案稍微紧凑一些,但更难理解,至少对于不熟悉 LINQ 的人来说是这样。
使用 for 循环,并使用string.Substring()方法提取字符,确保不会超出字符串的长度。
例如
string x = "1+2-3-2-3+";
const int LENGTH_OF_SPLIT = 2;
for(int i = 0; i < x.Length(); i += LENGTH_OF_SPLIT)
{
string temp = null; // temporary storage, that will contain the characters
// if index (i) + the length of the split is less than the
// length of the string, then we will go out of bounds (i.e.
// there is more characters to extract)
if((LENGTH_OF_SPLIT + i) < x.Length())
{
temp = x.Substring(i, LENGTH_OF_SPLIT);
}
// otherwise, we'll break out of the loop
// or just extract the rest of the string, or do something else
else
{
// you can possibly just make temp equal to the rest of the characters
// i.e.
// temp = x.Substring(i);
break; // break out of the loop, since we're over the length of the string
}
// use temp
// e.g.
// Print it out, or put it in a list
// Console.WriteLine(temp);
}