The following bit of C# code does not seem to do anything:
String str = "{3}";
str.Replace("{", String.Empty);
str.Replace("}", String.Empty);
Console.WriteLine(str);
This ends up spitting out: {3}. I have no idea why this is. I do this sort of thing in Java all the time. Is there some nuance of .NET string handling that eludes me?
There are numerous ways to replace all brackets in a string. We are going to use the simplest approach which involves the usage of the regex pattern as well as replace () method. The replace () method searches the string for a particular value or a regex pattern and it returns a new string with the replaced values.
We are calling replace () method and passing regex and hash symbol ( #) as parameters. As a result, it will replace all brackets in the string with hash symbol ( # ). The new string returned by this method will be stored in the result variable. We are displaying the result in the h1 element using the innerText property.
The replace () method searches the string for a particular value or a regex pattern and it returns a new string with the replaced values. In the following example, we have one global variable that holds a string.
You can use format strings. How format strings work is you add ' {} ' brackets to the string, and using the format function, we add variable in that order. They will be added to where the brackets lie. apple_price = 50 orange_price = 40 str = "Apple costs $ {} and Orange costs $ {}" print (str.format (apple_price, orange_price))
The String class is immutable; str.Replace
will not alter str
, it will return a new string with the result. Try this one instead:
String str = "{3}";
str = str.Replace("{", String.Empty);
str = str.Replace("}", String.Empty);
Console.WriteLine(str);
String is immutable; you can't change an instance of a string. Your two Replace() calls do nothing to the original string; they return a modified string. You want this instead:
String str = "{3}";
str = str.Replace("{", String.Empty);
str = str.Replace("}", String.Empty);
Console.WriteLine(str);
It works this way in Java as well.
Replace actually does not modify the string instance on which you call it. It just returns a modified copy instead.
Try this one:
String str = "{3}";
str = str.Replace("{", String.Empty);
str = str.Replace("}", String.Empty);
Console.WriteLine(str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With