c# : trimming a string

Started by
4 comments, last by ApochPiQ 17 years ago
I have a string with for example : "ABCDEFGHI" And I want to get a new string which has only the letters "AEI" So I do this :

string list = "AEI";
string temp1;

temp1 = temp.Trim(list.ToCharArray());  // first remove "AEI"

temp = temp.Trim(temp1.ToCharArray());  // then remove "BCDFGH" from the first string

But this code doesn't work. When I debug this temp1 still contains "ABCDEFGHI" Am I missing something here?!? :(
Advertisement
Yes. Trim() only removes leading and trailing characters.

What are you actually trying to do and what is your actual data set? This
string temp = "ABCDEFGHI";string result = String.Join("",temp.Split("BCDFGH".ToCharArray()));

does what you want rather concisely (but it's ugly!). There are likely better and more readable ways to do what you're really trying to do with your actual data set...
Moved to For Beginners.
I'm trying to get a new string with only some characters (in my case only numbers)

So if I have the following string

"hello 123 goodbye!"

I should get : "123"

and I thought the solution was first remove all the numbers "1234567890" so then I get : "hello goodbye"
and then I remove "hello goodbye" from "hello 123 goodbye" => "123"

But it seems I will have to write my own function for this :(
have a look into regular expressions ;)
One way to solve the problem:

public string StripDown(string originalstring, string leavecharacters){    StringBuilder ret = new StringBuilder(originalstring.Length);    foreach(char character in originalstring)    {        if(leavecharacters.IndexOf(character) >= 0)            ret.Append(character);    }    return ret.ToString();}// Example usagestring foo = "Test 7 8 6 1 Blah";MessageBox.Show(StripDown(foo, "1234567890"));



That's not a particularly efficient solution, though. For doing heavy-duty text work, regular expressions are a very handy tool, as AnthonyN1974 mentioned.

using System.Text.RegularExpressions;// Example usageRegex regex = new Regex("[^0-9]");string result = regex.Replace("Test 7 8 6 1 Blah", "");MessageBox.Show(result);

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

This topic is closed to new replies.

Advertisement