简体   繁体   中英

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 (eg "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

Simple. Just use the Split method:

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM