lost_in_the_source
lost_in_the_source

Reputation: 11237

How to split among two different characters

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

Answers (5)

Sudhakar Tillapudi
Sudhakar Tillapudi

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

Grant Winney
Grant Winney

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:

  • 3
  • 10
  • 5

Upvotes: 1

Zbigniew
Zbigniew

Reputation: 27594

You can use overloaded version of string.Split:

var splitted = x.Split(new [] { "*", "^" }, StringSplitOptions.None);

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

Have you tried using the Split method:

string x = "3*10^5";
string[] result = x.Split(new[] { '*', '^' });

Upvotes: 2

L.B
L.B

Reputation: 116118

var arr = "3*10^5".Split("*^".ToCharArray());

Upvotes: 3

Related Questions