• Advertisement
Sign in to follow this  

c# : trimming a string

This topic is 3978 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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?!? :(

Share this post


Link to post
Share on other sites
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...

Share this post


Link to post
Share on other sites
Moved to For Beginners.

Share this post


Link to post
Share on other sites
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 :(

Share this post


Link to post
Share on other sites
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 usage
string 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 usage
Regex regex = new Regex("[^0-9]");
string result = regex.Replace("Test 7 8 6 1 Blah", "");
MessageBox.Show(result);


Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement