Question

I want to split a string into an array. The string is as follows:

:hello:mr.zoghal:

I would like to split it as follows:

hello mr.zoghal

I tried ...

string[] split = string.Split(new Char[] {':'});

and now I want to have:

  string  something = hello ;
  string  something1 = mr.zoghal;

How can I accomplish this?

Was it helpful?

Solution

For your original request:

string myString = ":hello:mr.zoghal:";
string[] split = myString.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
var somethings = split.Select(s => String.Format("something = {0};", s));
Console.WriteLine(String.Join("\n", somethings.ToArray()));

This will produce

something = hello;
something = mr.zoghal;

in accordance to your request.

Also, the line

string[] split = string.Split(new Char[] {':'});

is not legal C#. String.Split is an instance-level method whereas your current code is either trying to invoke Split on an instance named string (not legal as "string" is a reserved keyword) or is trying to invoke a static method named Split on the class String (there is no such method).

Edit: It isn't exactly clear what you are asking. But I think that this will give you what you want:

string myString = ":hello:mr.zoghal:";
string[] split = myString.Split(new[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
string something = split[0];
string something1 = split[1];

Now you will have

something == "hello"

and

something1 == "mr.zoghal"

both evaluate as true. Is this what you are looking for?

OTHER TIPS

String myString = ":hello:mr.zoghal:";

string[] split = myString.Split(':');

string newString = string.Empty;

foreach(String s in split) {
 newString += "something = " + s + "; ";
}

Your output would be: something = hello; something = mr.zoghal;

It is much easier than that. There is already an option.

string mystring = ":hello:mr.zoghal:";
string[] split = mystring.Split(new char[] {':'}, StringSplitOptions.RemoveEmptyEntries);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top