I have a string that looks like this:
[ID] [LastName], [FirstName]
I want to fetch the ID, it consists of one or more digits. I'm guessing I have to find the first space of the string and then fetch the digit(s) before that space. If I understand things correctly I can't use Substring or IndexOf for this.

Any ideas on how to solve this? As always - I'm thankful for any help!

Try this out:

static void Main()
    {
        string str = "   123 Lname Fname";
        char[] strToParse = str.ToCharArray(); // convert string to array of chars
        char ch;
        int charpos = 0;    
        do          //skip whitespace except '\n'            
        {
            ch = strToParse[charpos]; 
            charpos++;            
        }            
        while (ch != '\n' && char.IsWhiteSpace(ch));
        charpos--; //Putback a char
        Console.WriteLine(strToParse[charpos]); // this will print the first digit of your ID: 1 in this case
        Console.ReadKey();       
    }

I just reworked some code from this snippet: http://www.daniweb.com/code/snippet217185.html

Thanks, ddanbe! I'm not sure I understand every line of the code, I mostly speak "newbie" :) I want every digit of the ID that's before the first space. What do I need to change in the code above to achieve that?

Well, you can find that in the snippet I gave you. I know it is perhaps somewhat above "newbie" level, but give it a try. Look at the lines between 131 and 171. If you cannot figure it out, please feel free to tell so. I or other people around here will be most happy to help you out:)

int myNumber = Int32.Parse(str.Trim().Substring(0, str.Trim().IndexOf(' ')));

This will attempt to convert the first text of the string into an integer. Leading spaces are ignored. If you know you don't have leading spaces, remove the Trim() calls.

ddanbe: I wasn't able to figure out your example, and to be honest it seems like an awful lot of code for a small function :) Thanks anyway!

Momerath: That's more along the lines of how I like to write code. I was obviously very wrong in my first post about Substring and IndexOf :) My thought was to loop through the string until I hit the blank space, count how many digits I had passed and use that number as an index. Your's is much better, thanks!

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.