Reputation: 11237
I have a string, like this:
string x="3*10^5";
and I need to split it among the '*' and '^' characters, so that its array form will contain
"3", "10", "5"
So I tried:
string x="3*10^5";
List<string> arr;
foreach(char i in x){
if(x[i].ToString()=="*")/*IndexOutOfRange Exception */{
arr= ToStringList(x.Split('*'));
}
else if(x[i].ToString()=="^"){
arr=ToStringList(x.Split('^'));
}
}
My function:
List<string> ToStringList(string[] arr){
List<string> w;
foreach(string i in arr){
w.Add(i);
}
return w;
}
But this code is throwing an IndexOutOf Range Exception How can I make one part of the array split by '*' character and another part by '^' character?
Upvotes: 1
Views: 91
Reputation: 26209
Solution 1: you can use String.Split()
method to perform splitting using multiple delimeters.
Try This:
string x="3*10^5";
string [] split = x.Split(new Char[] { '*', '^' });
Solution 2: if you have any empty string items you need to pass StringSplitOptions.RemoveEmptyEntries
as second argument to String.Split()
function to ignore the Split operation on Empty Items.
Try This:
string x="3*10^5";
string [] split = x.Split(new Char[] { '*', '^' },StringSplitOptions.RemoveEmptyEntries);
Upvotes: 1
Reputation: 66449
You can use string.Split to split your string on one or more characters that you specify:
string x = "3*10^5";
var parts = x.Split('*', '^');
The resulting string array contains:
Upvotes: 1
Reputation: 27594
You can use overloaded version of string.Split
:
var splitted = x.Split(new [] { "*", "^" }, StringSplitOptions.None);
Upvotes: 1
Reputation: 1038820
Have you tried using the Split
method:
string x = "3*10^5";
string[] result = x.Split(new[] { '*', '^' });
Upvotes: 2