String

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I have the following string:
"first, second, third, fourth, last"

And yet another one:
" yellow and blue , something,hello,nothing "

I would like to get all words and phrases and be sure to remove the
white spaces before and after ,

Then I would like to create some kind of list with it.

For example, string 2 would create the list:
yellow and blue
something
hello
nothing

Thanks,
Miguel
 
Howdy,

string[] phrases = System.Text.RegularExpresions.Regex.Split(input,
@"\s*,\s*");

Please note you have to handle empty entries yourself - "word1, , word2"
will produce
phrases[0] : "word1",
phrases[1] : String.Empty,
phrases[2] : "word2"

hope this helps

List<string> finalPhrases = new List<string>();

for (int i = 0; i < phrases.Length; i++)
{
string phrase = phrases;

if (pharse != String.Empty)
finalPhrases.Add(phrase);
}

For large amount of words it might not be effective, therefore it would be
better to construct a custom split function which loops through all the
characters and does the same what i propsed but skipping empty phrases (i
heard it's supported in .NET 3.0 but i cannot confirm that)

hope this helps
 
shapper said:
Hello,

I have the following string:
"first, second, third, fourth, last"

And yet another one:
" yellow and blue , something,hello,nothing "

I would like to get all words and phrases and be sure to remove the
white spaces before and after ,

Then I would like to create some kind of list with it.

For example, string 2 would create the list:
yellow and blue
something
hello
nothing

Thanks,
Miguel

Since you'll have to do string massaging and checking if you go the regular
expression route, try just doing it yourself...the following is an example:

private string[] GetPhrases(string Text)
{
string[] rawPhrases = Text.Split(',');
ArrayList phrases = new ArrayList();

foreach (string rawPhrase in rawPhrases) {
string phrase = rawPhrase.Trim();
if (phrase != string.Empty) {
phrases.Add(phrase);
}
}

return (string[]) phrases.ToArray(typeof(string));
}

Note: This is using .Net Framework v1.1 and so there are no generics being
used (otherwise, I would have used the generic version of the ArrayList).

HTH :)

Mythran
 
Back
Top