Multiple Characters Replacement using C#'s String.Replace method

Hi folks,I wondered if there is any way to replace multiple characters using the String.Replace() method only once instead of using it several times as I need for one string variable?It means, if I have one string with a lot of characters for replacement and I don’t want to write more than one code statement for such a operation.Thanks in advance,Yair Nevet
Yair Nevet
Microsoft MCAD.NET
0
YairNevet
11/24/2007 1:38:06 PM
asp.net.getting-started 91979 articles. 3 followers. Follow

11 Replies
2139 Views

Similar Articles

[PageSpeed] 49

Are you doing a many to one replacement or a many to many replacement?  

Example1:  original = "a string, with feelings - unwittingly.  A string;";  replaceChars = ",-.;"; replaceWith = ' ';   

                   replaced = original.split(replaceChars).join(replaceWith);

 

Example2: original = "a string, with feelings - unwittingly.  A string;";  replaceChars = ",-.;"; replaceWith = "?=*:";  

This one is harder (replace some characters with corresponding other characters.  It can be done if you don't mind doing some setup first.

see the page at :  http://msdn2.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace(VS.71).aspx and the example code.  If you use the regex.replace method with a matchevaluator providing what the replaced string will be you can use a switch statement or something similar to determine what was matched by your expression and what you want to replace it with.

Mark this as answered if it helped.   I look forward to seeing your solution otherwise.

--JJ 


Please mark as answered if I helped.
I don't answer personal emails unless I know you or of you. Feel free to post in the forum to get an answer from me.
0
jose_jimenez
11/24/2007 2:30:20 PM

Add the string.replace into a while loop or foreach() That should do the trick.


Cheers
Al
My Blog
MapStats.NET
Please click on 'Mark as Answer' if this post answered your question!
0
albertpascual
11/24/2007 2:32:31 PM

Well, I did it with a loop, but in each iteration it's is always brings me the original given string. 

How can I solve it?

Thanks,

 

Yair


Yair Nevet
Microsoft MCAD.NET
0
YairNevet
11/24/2007 8:06:09 PM

my code :):

 

1     public string strSqlBlocker(string StrValue)
2        {   
3            string[] BadCharacters = { "Hello", "World", "And", "How" };
4            string[] GoodCharacters = { "Goodbye", "Moon", "Without", "When" };
5            string strReplaced = "";
6    
7            int i;
8            for(i=0; i9            {
10               strReplaced = StrValue.Replace(BadCharacters[i], GoodCharacters[i]);
11           }
12   
13           return strReplaced;
14           
15       }
 
Yair Nevet
Microsoft MCAD.NET
0
YairNevet
11/24/2007 8:08:05 PM

Inside the loop do

mystring = mystring.Replace(ch);

So you always have the new string replacing the old. Makes sense?


Cheers
Al
My Blog
MapStats.NET
Please click on 'Mark as Answer' if this post answered your question!
0
albertpascual
11/24/2007 8:11:14 PM
It is definitely make a sense!Thanks dude!! You helped me! 

 


Yair Nevet
Microsoft MCAD.NET
0
YairNevet
11/24/2007 8:25:40 PM

No problems, anytime!

Happy coding


Cheers
Al
My Blog
MapStats.NET
Please click on 'Mark as Answer' if this post answered your question!
0
albertpascual
11/24/2007 9:34:51 PM

I didn't see if you answered Jose's question about one-to-many or many-to-one. If you want to replace multiple matches with a single replacement string this should work.

string phone = "800 123-1234";
// Strip "-" and " " from the phone number string.
phone = Regex.Replace(phone, @"[- ]", String.Empty);
Console.WriteLine(phone);
// output: 8001231234;
 

 Hope this helps.

Greg

 

0
GregoryJ2
12/3/2007 1:29:26 AM

This code is the same of above it was useful for me, in my case i had to read info from a text file and use thenumeric values but some times the info contained chars.

This is my example.

The name space is:  System.Text.RegularExpressions;

The code:

this.lblMensaje.Text = "CTEF080124";

this.lblMensaje.Text = Regex.Replace(lblMensaje.Text, @"[A-Z]", String.Empty);

//The final string 080124


José Luis Gonzalez
0
jlglez_armenta
4/30/2008 7:03:15 PM

how about this one,

let's say i have a string I open, i want to do the following:

replace "(b)" with "<strong>"

replace "(/b)" with "</strong>"

replace "\r\n" with "<br />"

and so on and so forth..

basically like text from a textbox for replying to a forum topic, where a LOT of "tags" will be replaced by real html tags.

 how should it be done?

0
wreck_of_u
6/10/2008 5:59:24 AM

Hey folks, I have a similar problem but i can not solved yet.
I have an aspx page with content and some kind of tokens like {{1}} {{2}}, and so on. Those numeric values are from a table and besides get another parameters from the web page like a customer id and language that are on sql tables too.

Now i have something like this:

myString = Regex.Replace(myString,
            _tokenStartTag + "(.*?)" + _tokenEndTag,
            new MatchEvaluator(Replace));

Where mystring is a stringbuilder with the content of all the aspx, tokenStartTag and End are the brackets constant, and the evaluator calls a function with the Replace name. In that function i use this line:

string key = token.Substring(_tokenStartTag.Length, token.Length - _tokenStartTag.Length - _tokenEndTag.Length);

And i just eliminate the brackest and have the numeric value, then i query two tables using a join where customer logged, language selected and this numeric value matched according my query. That give me a rowset and then i just need to replace that numeric value without the brackets with the coresponding text to that number from the results of the query.

That last thing is where i am stuck, i don't have idea of how to parse the numeric value i gaot, against the query results. Can anybody helpe please?

Thanks in advanced.

0
robecflo74
8/1/2008 5:40:54 PM
Reply:

Similar Artilces:

when using replace only replace the string if another string replacement takes place
Hello, Im using the string function to allow people to post images on my message board. im using the code below:         message = message.Replace("[img]", "<img src='");        message = message.Replace("[/img]", "' />"); This works fine, but it causes problems if only the [img] is input and not the [/img]. Does anyone know if it is possible to only do the first string replace if the second one is also found? thanks The simplest way would be to first check that the closing [/img] tag exists, and then do the r...

Replace 1's and 0's in a gridview column with Yes's and No's
Is it possible to change the display of a column in a gridview to show a Yes for all 1's and a No for 0's that display in a particular column of a gridview bound to a database?  If so, can someone share the way with me?  I am using ASP.NET 2.0 with VB Code Behind.  Thanks One way you can do is thrrough  CASE in your select statement: Select YesNoColumn= CASE yourColumn WHEN 1 THEN 'Yes' WHEN 0 THEN 'No' ELSE '' END FROM YourtableLimno <Columns>     <asp:TemplateField HeaderText="yourHeader" SortExpression="yourDataField"> ...

superreview requested: [Bug 123006] Keyword substitution with %s doesn't escape characters : [Attachment 139974] Encoding all characters for %s replacement (complete urlencoding); no encoding for %S
timeless@myrealbox.com (working) <timeless@bemail.org> has asked neil@parkwaycc.co.uk <neil.parkwaycc.co.uk@myrealbox.com> for superreview: Bug 123006: Keyword substitution with %s doesn't escape characters https://bugzilla.mozilla.org/show_bug.cgi?id=123006 Attachment 139974: Encoding all characters for %s replacement (complete urlencoding); no encoding for %S https://bugzilla.mozilla.org/attachment.cgi?id=139974&action=edit ...

superreview granted: [Bug 123006] Keyword substitution with %s doesn't escape characters : [Attachment 139974] Encoding all characters for %s replacement (complete urlencoding); no encoding for %S
neil@parkwaycc.co.uk <neil.parkwaycc.co.uk@myrealbox.com> has granted timeless@myrealbox.com (working) <timeless@bemail.org>'s request for superreview: Bug 123006: Keyword substitution with %s doesn't escape characters https://bugzilla.mozilla.org/show_bug.cgi?id=123006 Attachment 139974: Encoding all characters for %s replacement (complete urlencoding); no encoding for %S https://bugzilla.mozilla.org/attachment.cgi?id=139974&action=edit ------- Additional Comments from neil@parkwaycc.co.uk <neil.parkwaycc.co.uk@myrealbox.com> >+ shortcutURL =...

Re: [perl #35982] use of backslashed '-' following '$' within character class causes 'Use of uninitialized value in concatenation (.) or string' error under 'use warnings' pragma
--- yves orton via RT <perlbug-followup@perl.org> wrote: > On 5/26/05, demerphq <demerphq@gmail.com> wrote: > > On 26 May 2005 08:13:03 -0000, via RT fdhsbgeryft > lkjhuibfmfsi > > <perlbug-followup@perl.org> wrote: > ... > > > I hope I have been specific enough for you to > identify > > > this bug with relative ease, I have never > submitted a > > > bug before and I'm not exactly a professional > > > programmer > > Try www.perlmonks.org next time you suspect you've > found a bug...

C# .Replace() string replace failing
I'm reading a record from Sql Server (a text field) and displaying on a page. The copy in the text field is long and separated by paragraphs (manual line breaks). I want to read the field and convert the line breaks to <br> tags so everything displays correctly on the aspx page. I figure it would be easy, but I'm going nuts trying to figure this out. My code is below. <code>         // connect to db, query, bind             string SQL = "SELECT * FROM news WHERE id=" + ID;     &...

Replace asterisk(*) in string with String.Replace
Hi All, string FirstName = "James *"; FirstName = FirstName.Replace("*", "").Trim(); My desired output is "James" while the above code actually output "James *". Is it there is some tricks to replace an asterisk(*) character within a string? Thanks Check the below code    string test = "James *";   Response.Write(test.Replace("*"," ").TrimEnd()); HCHaissam Abdul MalakMCAD.NET| Blog | Hi stardust25, Your code is correct and It should work.   Hope this helps,  www.stockbiz.vnThe Vietnamese Stock Market and Economy Thanks both, I just...

superreview requested: [Bug 286718] mailnews spell check
neil@parkwaycc.co.uk <neil.parkwaycc.co.uk@myrealbox.com> has asked Scott MacGregor <mscott@mozilla.org> for superreview: Bug 286718: mailnews spell check - [Enter] no longer chooses 'replace' although 'replace' is 'active' button. https://bugzilla.mozilla.org/show_bug.cgi?id=286718 Attachment 177868: Fix last caller of Replace() https://bugzilla.mozilla.org/attachment.cgi?id=177868&action=edit ...

superreview granted: [Bug 286718] mailnews spell check
Scott MacGregor <mscott@mozilla.org> has granted neil@parkwaycc.co.uk <neil.parkwaycc.co.uk@myrealbox.com>'s request for superreview: Bug 286718: mailnews spell check - [Enter] no longer chooses 'replace' although 'replace' is 'active' button. https://bugzilla.mozilla.org/show_bug.cgi?id=286718 Attachment 177868: Fix last caller of Replace() https://bugzilla.mozilla.org/attachment.cgi?id=177868&action=edit ------- Additional Comments from Scott MacGregor <mscott@mozilla.org> FYI, I checked this change into Thunderbird as well. ...

superreview granted: [Bug 288638] get rid of 'character' member (of MozXftLangGroup) that's not used any more : [Attachment 179274] patch
David Baron <dbaron@mozilla.org> has granted Jungshik Shin <jshin1987@gmail.com>'s request for superreview: Bug 288638: get rid of 'character' member (of MozXftLangGroup) that's not used any more https://bugzilla.mozilla.org/show_bug.cgi?id=288638 Attachment 179274: patch https://bugzilla.mozilla.org/attachment.cgi?id=179274&action=edit ...

superreview requested: [Bug 288638] get rid of 'character' member (of MozXftLangGroup) that's not used any more : [Attachment 179274] patch
Jungshik Shin <jshin1987@gmail.com> has asked David Baron <dbaron@mozilla.org> for superreview: Bug 288638: get rid of 'character' member (of MozXftLangGroup) that's not used any more https://bugzilla.mozilla.org/show_bug.cgi?id=288638 Attachment 179274: patch https://bugzilla.mozilla.org/attachment.cgi?id=179274&action=edit ...

Replacing multiple characters in a string
I am just wondering how do I check string for presence od various characters and replace them. I know the replace method but I only know how to check for a single character e.g. errString.replace("$","-") Can anyone tell me how do I do this with multiple charachters? :-( Thanks. You should use Regular Expression to this end. Here is a good link. Here is an example: Dim RegExp As RegEx Dim str As String RegExp = New RegEx("[aeiou]") str = "The slow-moving aardwark" Response.Write( RegExp.Replace( str, "?") This w...

multiple SMTP's and different IP's, domain names to send email from this server using different SMTP's
Is anybody can help me with this 2 issues we have: 1. We need to have multiple SMTP's installed on our server - how do you do that 2. We need to rotate different IP's, domain names to send email from this server using different SMTP's          Thanks   Third party mail server.  Look at Smartermail or iMail, Exchange if you need that much. JeffPlease: Don't forget to click "Mark as Answer" on the post that helped you. That way future readers will know which post solved your issue. Is this only option? &n...

superreview requested: [Bug 232503] Start using Empty[C]String() : [Attachment 140140] Use Empty[C]String()
Johnny Stenback <jst@mozilla.jstenback.com> has asked Peter Van der Beken <peterv@propagandism.org> for superreview: Bug 232503: Start using Empty[C]String() http://bugzilla.mozilla.org/show_bug.cgi?id=232503 Attachment 140140: Use Empty[C]String() http://bugzilla.mozilla.org/attachment.cgi?id=140140&action=edit ...

Web resources about - Multiple Characters Replacement using C#'s String.Replace method - asp.net.getting-started

Chemistry and Metallurgy Research Replacement Facility - Wikipedia, the free encyclopedia
The Chemistry and Metallurgy Research Replacement Facility , usually referred to as the CMRR , is a facility under construction at Los Alamos ...

Unsportsmanlike Conduct Called On Replacement NFL Ref Due To Facebook Posts
One of the National Football League ’s replacement officials was removed from his assignment to work the New Orleans Saints ’ visit to the Carolina ...

Facebook Home: Replacement Home Screen for Android
Nicely-designed phone interface that I would personally never want to use. (They’re embedding Helvetica rather than using Google’s crummy Roboto. ...

The Replacements (@TheReplacements) on Twitter
Website has been fixed. Stay tuned to see what other shenanigans we may or may not have up our sleeves... theReplacementsOfficial.

App Store - The Complete Hair Replacement Guide
Get The Complete Hair Replacement Guide on the App Store. See screenshots and ratings, and read customer reviews.

Nexus 4 Screen Replacement + Frame/Bezel Exchange - YouTube
For the parts or tools needed to perform this repair visit http://www.repairsuniverse.com/lg-nexus-4-e960-screen-replacement-repair-parts.ht ...

'Demtel man' Tim Shaw announced as Mark Parton's replacement on 2CC
... breakfast host. But wait, there's more... 2CC has a new breakfast host to replace the outgoing Mark Parton ; but wait, there's more. His replacement ...

Big Bash League: Sydney Sixers' Jackson Bird ready to soar as Brett Lee's replacement
Jackson Bird says it's a mistake to compare him to Brett Lee, but if the Victorian had Lee's speed he'd likely be in Australia's attack for the ...

Big Bash League: Dick Smith collapse leaves Melbourne Stars searching for replacement key sponsor
... tumultuous week is on the cusp of returning to positive territory, with the Big Bash League team closing in on what would be a rapid replacement ...

Soundwave cancellation: Plan emerges to crowdfund replacement mini-festival
Bands unite to organise replacement concert tour to Soundwave Music Festival.

Resources last updated: 1/7/2016 6:56:34 AM