-1

I have a string that looks something like:

0122031203

I want to be able to parse it and add the following into a list:

01
22
03
12
03

So, I need to get each 2 characters and extract them.

I tried this:

 List<string> mList = new List<string>();
 for (int i = 0; i < _CAUSE.Length; i=i+2) {
     mList.Add(_CAUSE.Substring(i, _CAUSE.Length));
 }
 return mList;

but something is not right here, I keep getting the following:

Index and length must refer to a location within the string. Parameter name: length

Did I get this wrong?

Jacob Parker
  • 2,546
  • 18
  • 31
Madam Zu Zu
  • 6,437
  • 19
  • 83
  • 129
  • 1
    It's great to use the debugger and particular the intermediate window to understand why things like this aren't working. Like looking at `_CAUSE.Substring(i, _CAUSE.Length)` for example. – WiredPrairie Mar 18 '13 at 18:09
  • Here are some reusable solutions: http://stackoverflow.com/questions/4133377/splitting-a-string-number-every-nth-character-number – WiredPrairie Mar 18 '13 at 18:16

4 Answers4

2

How about using Linq?

string s = "0122031203";
int i = 0;
var mList = s.GroupBy(_ => i++ / 2).Select(g => String.Join("", g)).ToList();
I4V
  • 34,891
  • 6
  • 67
  • 79
1

I believe you have may have specified the length incorrectly in the Substring function.

Try the following:

List<string> mList = new List<string>();

for (int i = 0; i < _CAUSE.Length; i = i + 2)
{
    mList.Add(_CAUSE.Substring(i, 2));
}

return mList;

The length should be 2 if you wish to split this into chunks of 2 characters each.

Martin
  • 16,093
  • 1
  • 29
  • 48
0

when you do the substring, try _CAUSE.SubString(i, 2).

hak
  • 11
  • 3
0

2points: 1) as previously mentioned, it should be substring(i,2); 2) U should consider the case when the length of ur string is odd. For example 01234: do u want it 01 23 and u'll discard the 4 or do u want it to be 01 23 4 ??

Reem
  • 43
  • 7