1

I have an array of strings, each element of the array contains a date and a last name, separated by a single space. For example the array at position 1 contains "12/10/2012 Smith" I simply need the date for each position in the array. Can I do this using Substring()? Or does that not work for arrays?

            for(int i = 0; i < array.Length; i++) {
                if(array[i] == ' ') {
                    array[i].Substring(0, i);
                }
                Console.WriteLine (array[i]);
            }

This doesn't work. Do I need to somehow look at each of the characters in the array to use Substring()?

2
  • Is array your array of strings here or the string itself? Substring will work on a string object. If you have a string object, you will need to loop through the array and get the individual string. Also, have you looked at string.split ? It will avoid one loop for you. Commented Dec 10, 2012 at 6:27
  • array is the actual array. I was thinking the same thing, but I wasn't sure. I will try to loop through each element in the array and maybe use string.Split() Commented Dec 10, 2012 at 6:34

2 Answers 2

5

If you have an array of strings array[i].Split(' ')[0]; will split an element, and element [0] will be the date portion.

This assumes your data is perfectly formed, as you have specified. You may wish to add checks to prevent index errors.

Sign up to request clarification or add additional context in comments.

4 Comments

Maybe it would be better to use regex: \d+/\d+/\d+? Not completely secure but still some kind of validation.
That's an interesting way to do it. Are you saying that I can just replace the if statement with array[i].Split(' ')[0];?
Why do you need an if statement? Just take what Alan has given and use it in your writeline.
Oh wow, forgive me, I see it now. Thanks for you help, guys :)
1

Try this:

foreach(string item in array)
{
  string yourDate=item.Split(' ')[0];
  string yourName=item.Split(' ')[1];
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.