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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Remove spaces 1
Remove first word of a string 2
Enum TypeConverter 3
Generic List to String 3
String 2
Table Format to Hold Data 16
Extending Dictionary 2
String 1

Back
Top