Hi there, how can I split a string into variables?? better:

    string s = "one,two,three,four";

           // Split string on character comma.
    string[] words = s.Split(',');
    foreach (string word in words)
    {
        Console.WriteLine(word);
    }

how can I put an incrasing variable (for n splitted words) instead of 'Console.WriteLine(word)'

thanks

Recommended Answers

All 5 Replies

Well you could parse the c-string with strtok.

Well you could parse the c-string with strtok.

And why would you rely on a simple C function in a managed language?

how can I put an incrasing variable (for n splitted words) instead of 'Console.WriteLine(word)'

I honestly have no idea what you're asking here. Could you elaborate?

And why would you rely on a simple C function in a managed language?

Because this thread was originally posted in the C forum and gerard probably didn't notice that the code was C#.

how can I put an incrasing variable (for n splitted words) instead of 'Console.WriteLine(word)'

you already have your "incasing" variable -- words. maybe I don't understand your question.

words is your variable; it's an array of variables. you would reference the variables with index notation:

words[0], words[1], words[2], etc...

you can also use the StringBuilder class if you are going to be using a large amount of words. It's more efficient and has more methods/properties to work with.

Example:

StringBuilder words = new StringBuilder();

foreach(string word in words)
    words.Append(word);

I know this is solved, but I wanted to post this piece of code I use all the time and love to use (mainly used when reading in a document or something but works here)

string s = "one,two,three,four";
List<string> words = new List<string>();
words.AddRange(s.Split(new String [] { "," }StringSplitOptions.RemoveEmptyEntries));

This code above takes a string and then splits it up in a list. When parsing through the string, if it comes onto a comma it creates a new index.

So in otherwords, for every comma, a new index is made and the string is broken up. Again I love using this code (I actually think I got it from DaniWeb years back), and use it all the time.

By the way Lists don't need a preset size to work (unlike arrays), and can be expanded and shrunk as you desire, and they work just like an array when it comes to indexing (I used to use arrays hardcore till I learned of Lists, and haven't turned back). If you are curious about Lists, PM me I'll explain some of the basic commands

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.