Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
String Manipulation
Message
De
28/06/2010 13:42:57
 
 
À
28/06/2010 13:36:40
Information générale
Forum:
ASP.NET
Catégorie:
Code, syntaxe and commandes
Versions des environnements
Environment:
C# 3.0
Divers
Thread ID:
01470812
Message ID:
01470832
Vues:
38
>>>>>>>>Hi,
>>>>>>>>
>>>>>>>>I have a string like this:
>>>>>>>>
>>>>>>>>"LastName, FirstName, MiddleName"
>>>>>>>>
>>>>>>>>and sometimes it could just be this:
>>>>>>>>
>>>>>>>>"CompanyName"
>>>>>>>>
>>>>>>>>I want to add a string into these strings so they end up like this:
>>>>>>>>
>>>>>>>>"LastName DESC, FirstName DESC, MiddleName DESC"
>>>>>>>>
>>>>>>>>or:
>>>>>>>>
>>>>>>>>"CompanyName DESC"
>>>>>>>>
>>>>>>>>How would I do this in C#?
>>>>>>>
>>>>>>>Basically this
>>>>>>>
>>>>>>>			string s = "LastName, FirstName, MiddleName";
>>>>>>>
>>>>>>>			s = s.Replace(",", " DESC,") + " DESC";
>>>>>>>
>>>>>>
>>>>>>I don't think that works in the case of "CompanyName"
>>>>>
>>>>>
>>>>>So far this is what I have come up with (SortOrder could either be "ASC" or "DESC"):
>>>>>
>>>>>
            string s = "LastName, FirstName, MiddleName";
>>>>>            string[] Split = s.Split(new Char[] { ',' });
>>>>>
>>>>>            string NewSortExpression = "";
>>>>>            int i = 0;
>>>>>            foreach (string st in Split)
>>>>>                NewSortExpression = NewSortExpression + st + " " + SortOrder + ",";
>>>>>
>>>>>            // get rid of last ","
>>>>>            NewSortExpression = NewSortExpression.Substring(0, NewSortExpression.Length - 1);
>>>>
>>>>using a stringbuilder may not be a bad idea
>>>>
>>>>
>>>>       static void Main(string[] args)
>>>>        {
>>>>
>>>>			string s = "LastName, FirstName, MiddleName";
>>>>
>>>>			string[] split = s.Split(new Char[] { ',' });
>>>>
>>>>			string newSortExpression;
>>>>
>>>>			string sortOrder = "DESC";
>>>>
>>>>			StringBuilder sb = new StringBuilder();
>>>>
>>>>			foreach (string st in split)
>>>>			{
>>>>				sb.Append(st);
>>>>				sb.Append(' ');
>>>>				sb.Append(sortOrder);
>>>>				sb.Append(',');
>>>>			}
>>>>
>>>>
>>>>			// get rid of last ","
>>>>			sb.Length--;
>>>>
>>>>			newSortExpression = sb.ToString();
>>>>			Console.WriteLine("{0}", newSortExpression);
>>>>
>>>>			Console.ReadLine();
>>>>          
>>>>        }
>>>>
>>>
>>>Would you recommend this over the much shorter one liner?
>>
>>
>>I would use the one-liner. But since I saw your loop. I wanted to show the StringBuilder as well
>
>OK, thanks a lot.


Using StringBuilder is for rather heavy string manipulation. The purpose is to avoid creating strings - that go on the heap and need to be recollected afterwards

But the one liner only creates one string too many
Gregory
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform