Sign in to follow this  
da_cobra

c# : trimming a string

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
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
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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this