Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Comma Seperated List String 1

Status
Not open for further replies.

autumnEND

Programmer
Nov 1, 2005
61
GB
Im trying to build up a string using substrings, and if there are more than one substring seperate them with a comma.

The maximum number of possible substrings is 7

Below is an example of how i get the string value

if (Convert.ToInt32(dr["country_england"]) == 1)
{
strEng = "England";
}

the final string will be :

strAreas = strEngland + strWales + strScotland etc

what would be the best way to build up the string, and to seperate them with a comma if there is more than one substring .

Any help would be greatly appreciated, Thanks.
 
I managed to sort it , by creating a function that added a comma and then remove the comma if its not needed.

private bool addComma()
{
if (strAreas != "")
{
strAreas += "," ;
strAreasTrim = strAreas.TrimEnd(',');
return true;
}

}

Im sure theres possibly a better way to do it, but it works for now .
 
I know you said you'd sorted out your prob but this is what I tend to do:


string a = "a," + "b," + "c,";

string b = a.Substring( 0, a.LastIndexOf( ',' ) );

Cheers
 
thanks for the reply, ill give that a try, it seems a better idea compaired to the solution i came up with, thanks again .
 
You could also have a look at the .Join method of string which will do what you require.


Hope this helps.

[vampire][bat]
 
Because .net strings are immutable, you might want to consider using StringBuilder, much cheaper to use.
Code:
System.Text.StringBuilder bufTxt = new StringBuilder();
...

// Here you get a little overhead evaluating the conditions
// but much less compared to TrimEnd() because it's actually
// returning a new string object without the ending character
// making it appear as if trimmed.
if(strEngland.Length > 0) {
  if(bufTxt.Length > 0) bufTxt.Append(",");
  bufTxt.Append( strEngland );
}
 
elegant solution to a perennial problem.

now, why didn't i think of that?



mr s. <;)

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top