string copying

  • Thread starter Thread starter dani kotlar
  • Start date Start date
D

dani kotlar

Is there a function that copies between string (or stringbuilder)
objects, while filtering out certain types or designated characters,
or leaving a certain typa of designates\d characters? For example, I
want to copy only the alphanumeric characters, or I want to copy a
string without the spaces.
Thanks
 
dani kotlar said:
Is there a function that copies between string (or stringbuilder)
objects, while filtering out certain types or designated characters,
or leaving a certain typa of designates\d characters? For example, I
want to copy only the alphanumeric characters, or I want to copy a
string without the spaces.

To copy a string without the spaces:

string theOriginal = "String with spaces";
string theCopy = theOriginal.Replace(" ","");

With a StringBuilder:

StringBuilder theOriginal = new StringBuilder("Strign with spaces");
theOriginal.Replace(" ", "");
string theCopy = theOriginal.ToString();

To remove "a" and "b" characters:

string theCopy = theOriginal.Replace("a","").Replace("b","");

If the combination of characters that you want to remove gets more
complex than this, it's time to start studying Regular Expressions (RegEx
class).
 
dani said:
Is there a function that copies between string (or stringbuilder)
objects, while filtering out certain types or designated characters,
or leaving a certain typa of designates\d characters? For example, I
want to copy only the alphanumeric characters, or I want to copy a
string without the spaces.
Thanks

You can use a regular expression to remove characters from a string.

This will remove everything but alphanumeric characters:

string filtered = Regex.Replace(original, "[^\dA-Za-z]+", string.Empty);

[] creates a set
^ makes it a negative set
\d matches a digit
A-Za-z matches a letter
+ repeats one or more times

So the pattern matches every group of characters (one or more) that is
not an alphanumeric, and replaces it with an empty string.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top