-1

文字列に 2 文字ごとに格納する方法はありますか?

例えば

1+2-3-2-3+

したがって、「1+」、「2-」、「3-」、「2-」、「3+」は、個別の文字列または配列になります。

4

3 に答える 3

4

最も簡単な方法は、ループを使用して文字列をたどり、現在の位置から 2 文字の部分文字列を取得することです。

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();

2 番目のソリューションはややコンパクトですが、少なくとも LINQ に精通していない人にとっては理解しにくいものです。

于 2013-03-26T01:41:19.877 に答える
1

これは、正規表現の良い問題です。あなたは試すことができます:

\d[+-]

その正規表現 ( HINT ) をコンパイルする方法を見つけて、すべての出現を返すメソッドを呼び出すだけです。

于 2013-03-26T01:46:07.843 に答える
0

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);
}
于 2013-03-26T01:52:01.740 に答える