Reputation: 1779
My code is:
public void processData(string data)
{
string com = data.Split(' ')[0];
string[] val = data.Remove(0,com.Length).Split(' ');
}
What I want to achieve using this code is that when com
stores the first word from the data
variable, the val
array should store the remaining words of the data
variable. In 4th line of code, I achieved this by first removing the character from 0 index to the length of the first word. This will remove the first word and then it will split it according to whitespaces and then store the result in array. The problem is that this in not happening. the com
is storing the first word but the val
is showing always null. Please some one tell me what to do? I can achieve this using foreach
loop or other techniques. But I don't want much code due to performance issues.
My example strings are like this:
begin main
timesteps 1750
weeks 250
campaigns 6
scenario 10
epsilon 0.01
powerplant1 11
powerplant2 10
constraint13 46
constraint14 7
constraint15 0
constraint16 1
constraint17 3
constraint18 0
constraint19 1
constraint20 1
constraint21 1
durations 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24
There are fields on left and values on right. I want to separately store them.
Example: field is timesteps
and value is 1750
Solution:
This was pretty dumb solution but I just restarted my Visual Studio and it worked fine.
Thanks all for your nice responses. I +1 all answers and marked Blachshma answer since the suggestion to restart or recreate the project was came from him.
Upvotes: 0
Views: 8607
Reputation: 17385
Use LINQ's Skip()
string[] val = data.Split(' ').Skip(1).ToArray();
To emphasis with a string from your example:
string data = "timesteps 1750";
string com = data.Split(' ')[0]; // Returns timesteps
string[] val = data.Split(' ').Skip(1).ToArray(); // Returns 1750
Another of your examples:
string data = "durations 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24 24";
com
will have "durations" and val
will have an array of 16 elements, each with the value of "24"
Upvotes: 5
Reputation: 460098
I assume that it val
does not show null
but the first word is empty since you have removed the substring of the first word from the string, but you have not removed the separator(white-space).
So this should work(if you just want to remove the first word):
string[] val = data.Split().Skip(1).ToArray();
Upvotes: 1
Reputation: 12439
string[] val = data.Remove(0, data.IndexOf(' ') + 1).Split(' ');
Upvotes: 3