Mislav Javor
Mislav Javor

Reputation: 1449

How to break a single string into an array of strings?

I have a program in which I read from a string that's formatted to have a specific look. I need the numbers which are separated by a comma (e.g. "A,B,D,R0,34,CDF"->"A","B","D","R0", "34", "CDF"). There are commas between letters that much is guaranteed I have tried to do (note: "variables" is a 2D char array, newInput is a string which is a method argumend, k and j are declared and defined as 0)

for(int i=0; i<=newInput.Length; i++){
            while(Char.IsLetter(newInput[i])){
                variables[k,j]=(char)newInput[i];
                i++;
                k++;
            }
            k=0;j++;

        }

with multi-dimensional character arrays. Is there a way for this to be done with strings? Because char arrays conflict with many parts of the program where this method has already been implemented

Upvotes: 6

Views: 191

Answers (3)

ganji
ganji

Reputation: 854

if you want to Split the string on line breaks use this

string str = "mouse\r\dog\r\cat\r\person\r\pig";
string[] lines = Regex.Split(str, "\r\n");

and if you want to split with chars , as input ,Split takes array of chars

char[] myChars = {':', ',', '.', '\u', ' ' };
string myString = "jack:tom kasra\unikoo car,pencil ball";
string[] myWords = myString.Split(myChars);

Upvotes: 3

Raging Bull
Raging Bull

Reputation: 18757

Try this:

 string MyString="A,B,D,R0,34,CDF";
 string[] Parts = MyString.Split(',');

And use them like:

Parts[0];//A
Parts[1];//B
Parts[2];//D
Parts[3];//R0
Parts[4];//34
Parts[5];//CDF

If you want to know more about Split function. Read this.

Upvotes: 3

p.s.w.g
p.s.w.g

Reputation: 149050

Simple. Just use the Split method:

var input = "A,B,D,R0,34,CDF";
var output = input.Split(','); // [ "A", "B", "D", "R0", "34", "CDF" ]

Upvotes: 8

Related Questions