tags:

views:

148

answers:

2

I have a string which consists of different fields. So what I want to do is get the different text and assign each of them into a field.

ex: Hello Allan IBM

so what I want to do is:

put these three words in different strings like

string Greeting = "Hello"
string Name = "Allan"
string Company = "IBM"

//all of it happening in a loop.
string data = "Hello Allan IBM"
string s = data[i].ToString();
string[] words = s.Split(',');
foreach (string word in words) {
    Console.WriteLine(word);
}

any suggestions? thanks hope to hear from you soon

+2  A: 

If I understand correctly you have a string with place-holders and you want to put different string in those place-holders:

var format="{0}, {1} {2}. How are you?";

//string Greeting = "Hello"
//string Name = "Allan"
//string Company = "IBM"

//all of it happening in a loop.
string data = ...; //I think you have an array of strings separated by ,

foreach( va s in data){
{
    //string s = data[i];//.ToString(); - it is already a string array
    string[] words = data[i].Split(',');

    Console.WriteLine(format, words[0], words[1], words[2]);
}
TheVillageIdiot
+1  A: 

To me it sound not like a problem that can be solved with a loop. The essential problem is that the loop can only work if you do exactly the same operation on the items within the loop. If your problem doesn't fit, you end up with a dozen of lines of code within the loop to handle special cases, what could have been written in a shorter way without a loop.

If there are only two or three strings you have to set (what should be the case if you have named variables), assign them from the indexes of the split string. An alternative would be using regular expressions to match some patterns to make it more robust, if one of the expected strings is missing.

Another possibility would be to set attributes on members or properties like:

[MyParseAttribute(/*position*/ /*regex*/)]
string Greeting {get;set;}

And use reflexion to populate them. Here you could create a loop on all properties having that attribute, as it sounds to me that you are eager to create a loop :-)

jdehaan