Reputation: 61
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()?
Upvotes: 1
Views: 97
Reputation: 3198
Try this:
foreach(string item in array)
{
string yourDate=item.Split(' ')[0];
string yourName=item.Split(' ')[1];
}
Upvotes: 1
Reputation: 46903
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.
Upvotes: 5