問題があります。文字列"3d8sAdTd6c"
があり、それを分割する必要があるため、結論は次のようになります。
3d
8s
Ad
Td
6c
これを行う方法を教えていただければ、とても感謝しています。
多分:
string[] result = str
.Select((c, index ) => new{ c, index })
.GroupBy(x => x.index / 2)
.Select(xg => string.Join("", xg.Select(x => x.c)))
.ToArray();
これは、2 文字ごとにグループ化string.Join
し、それらを文字列に連結するために使用します。
文字列を 2 つの文字のペアに分割するには、次のようにします。
/// <summary>
/// Split a string into pairs of two characters.
/// </summary>
/// <param name="str">The string to split.</param>
/// <returns>An enumerable sequence of pairs of characters.</returns>
/// <remarks>
/// When the length of the string is not a multiple of two,
/// the final character is returned on its own.
/// </remarks>
public static IEnumerable<string> SplitIntoPairs(string str)
{
if (str == null) throw new ArgumentNullException("str");
int i = 0;
for (; i + 1 < str.Length; i += 2)
{
yield return str.Substring(i, 2);
}
if (i < str.Length)
yield return str.Substring(str.Length - 1);
}
使用法:
var pairs = SplitIntoPairs("3d8sAdTd6c");
結果:
3D 8秒 広告 Td 6c
以下のようなものがループで動作するはずです。
string str = "3d8sAdTd6c";
string newstr = "";
int size = 2;
int stringLength = str.Length;
for (int i = 0; i < stringLength ; i += size)
{
if (i + size > stringLength) size = stringLength - i;
newstr = newstr + str.Substring(i, size) + "\r\n";
}
Console.WriteLine(newstr);
string input = "3d8sAdTd6c";
for (int i = 0; i < input.Length; i+=2) {
Console.WriteLine(input.Substring(i,2));
}