String.Replace(oldValue, newValue) -- not working - c#

Here is my code:
//I want to find the oldValue
string oldValue = "##OfferTitle##";
//In this string:
stringToReplace = "123##OfferTitle##456";
string newValue = "Test Offer Title";
//and return it in this variable as "123Test Offer Title456"
var newString = stringToReplace .Replace(oldValue, newValue );
return newString ;
The above is not working. All I get back is the original string.
I expect: "123Test Offer Title456"
But I get stringToReplace ("123##OfferTitle##456") unchanged or unmodified. What am I missing?

Please read the documentation carefully String.Replace Method (String, String):
Returns a new string in which all occurrences of a specified string in
the current instance are replaced with another specified string.
Strings are immutable in C#. Original string will stay unchanged.

Related

Is there a way to replace the arguments in a string multiple times?

I'm declaring a string at initialisation as follows
string a = string.Format("Hello {0}", "World.");
Is there a way to subsequently replace the zeroth argument for something else?
If there's no obvious solution, does anybody know of a better way to address the issue. For context, at initialisation I create a number of strings. The text needs to be updated as the program proceeds. I could create a structure comprising an array of strings and an array of objects and then build the final string as required, but this seems ugly, particularly as each instance could have a different number of arguments.
For example,
public class TextThingy
{
List<String> strings;
List<String> arguments;
...
public string ToString()
{
return strings[0] + arguments [0] + strings [1] ...
}
I've tried this, but to no avail.
string b = string.Format(a, "Universe.");
I guess that the argument {0} once populated is then baked into the string that one time.
You could move the format string to a variable like this?
Would that work? If not, please add some more info for us.
string fmt = "Hello {0}";
string a = string.Format(fmt, "World.");
string b = string.Format(fmt, "Universe.");
try string replace, like ...
StringBuilder sb = new StringBuilder("11223344");
string myString =
sb
.Replace("1", string.Empty)
.Replace("2", string.Empty)
.Replace("3", string.Empty)
.ToString();

Why does the Insert() Method remove zeros

I'm trying to format a string to a time string format. The PadLeft method is working but after that method I use the Insert method and for some reason it removes the zeros added by the PadLeft:
var formatString = data.Rows[i][j].ToString().PadLeft(6, '0');
formatString = data.Rows[i][j].ToString().Insert(1, ":").Insert(4, ":");
data.Rows[i][n] = formatString;
After the second line of code, the zeros are removed and the colons are added when the Insert method executes.
Hope I explained it thoroughly
String in .Net is immutable. Your first line returns a new string and does not modify the value in the table. So you need to continue working with that string and not the value in the table.
var formatString = data.Rows[i][j].ToString().PadLeft(6, '0');
formatString = formatString.Insert(1, ":").Insert(4, ":");
data.Rows[i][n] = formatString;
You have the zeroes in the formatString variable, and then, in the second line, you are assigning a new value to that variable, I think you want to do something like:
var formatString = data.Rows[i][j].ToString().PadLeft(6, '0');
formatString = formatString.Insert(1, ":").Insert(4, ":");
data.Rows[i][n] = formatString;

Interpolate a string retrieved from a file? [duplicate]

I can do this:
var log = string.Format("URL: {0}", url);
or even like this
var format = "URL: {0}";
...
var log = string.Format(format, url);
I have a format defined somewhere else and use the format variable, not inline string.
In C# 6, this is seems impossible:
var format = $"URL: {url}"; // Error url does not exist
...
var url = "http://google.com";
...
var log = $format; // The way to evaluate string interpolation here
Is there anyway to use string interpolation with variable declared earlier?
C# 6 seems interpolate the string inline during compile time. However consider using this feature for localization, define a format in config or simply having a format const in a class.
No, you can't use string interpolation with something other than a string literal as the compiler creates a "regular" format string even when you use string interpolation.
Because this:
string name = "bar";
string result = $"{name}";
is compiled into this:
string name = "bar";
string result = string.Format("{0}", name);
the string in runtime must be a "regular" format string and not the string interpolation equivalent.
You can use the plain old String.Format instead.
One approach to work around that would be to use a lambda containing the interpolated string. Something like:
Func<string, string> formatter = url => $"URL: {url}";
...
var googleUrl = "http://google.com";
...
var log = formatter(googleUrl);
In C# 7.0, you could use a local function instead of a lambda, to make the code slightly simpler and more efficient:
string formatter(string url) => $"URL: {url}";
...
var googleUrl = "http://google.com";
...
var log = formatter(googleUrl);
String interpolation is not library, but a compiler feature starting with C# 6.
The holes are not names, but expressions:
var r = new Rectangle(5, 4);
var s = $"Area: {r.Width * r.Heigh}":
How would you do that for localization, as you intend to?
Even r only exists at compile time. In IL it's just a position on the method's variable stack.
I've done what you intend to do for resources and configuration files.
Since you can only have a finite set of "variables" to substitute, what I did was have an array (or dictionary, if you prefer) and use a regular expression to replace the names in the holes with its index. What I did even allowed for format specifiers.
This is supposed to be a comment to the answer from i3arnon but I do not have the reputation :-( :
But for those who come to this old thread, in string.Format the format can be a variable:
string name = "bar";
string format = "{0}";
string result = string.Format(format, name);
works.
More of an idea as opposed to an answer.
For the example shown in the question, you can do the following.
var format = "URL: ";
...
var url = "http://google.com";
...
var result= $"{format} {url}";
I have an actual project where I have to do something like this a lot:
var label = "Some Label";
var value = "SomeValue";
//both label & value are results of some logic
var result = $"{label}: {value}";
You can with the right Nuget package: https://www.nuget.org/packages/InterpolatedStringFormatter
var mystring = "a thing(and something {other})";
Console.WriteLine(mystring.Interpolate("else"));
Outputs:
a thing(and something else)
It seems that you can do it like this:
var googleUrl = "http://google.com";
var url = $"URL: {googleUrl}";
System.Console.WriteLine(url);
You can check for more details in https://msdn.microsoft.com/en-us/library/dn961160.aspx

String Interpolation with format variable

I can do this:
var log = string.Format("URL: {0}", url);
or even like this
var format = "URL: {0}";
...
var log = string.Format(format, url);
I have a format defined somewhere else and use the format variable, not inline string.
In C# 6, this is seems impossible:
var format = $"URL: {url}"; // Error url does not exist
...
var url = "http://google.com";
...
var log = $format; // The way to evaluate string interpolation here
Is there anyway to use string interpolation with variable declared earlier?
C# 6 seems interpolate the string inline during compile time. However consider using this feature for localization, define a format in config or simply having a format const in a class.
No, you can't use string interpolation with something other than a string literal as the compiler creates a "regular" format string even when you use string interpolation.
Because this:
string name = "bar";
string result = $"{name}";
is compiled into this:
string name = "bar";
string result = string.Format("{0}", name);
the string in runtime must be a "regular" format string and not the string interpolation equivalent.
You can use the plain old String.Format instead.
One approach to work around that would be to use a lambda containing the interpolated string. Something like:
Func<string, string> formatter = url => $"URL: {url}";
...
var googleUrl = "http://google.com";
...
var log = formatter(googleUrl);
In C# 7.0, you could use a local function instead of a lambda, to make the code slightly simpler and more efficient:
string formatter(string url) => $"URL: {url}";
...
var googleUrl = "http://google.com";
...
var log = formatter(googleUrl);
String interpolation is not library, but a compiler feature starting with C# 6.
The holes are not names, but expressions:
var r = new Rectangle(5, 4);
var s = $"Area: {r.Width * r.Heigh}":
How would you do that for localization, as you intend to?
Even r only exists at compile time. In IL it's just a position on the method's variable stack.
I've done what you intend to do for resources and configuration files.
Since you can only have a finite set of "variables" to substitute, what I did was have an array (or dictionary, if you prefer) and use a regular expression to replace the names in the holes with its index. What I did even allowed for format specifiers.
This is supposed to be a comment to the answer from i3arnon but I do not have the reputation :-( :
But for those who come to this old thread, in string.Format the format can be a variable:
string name = "bar";
string format = "{0}";
string result = string.Format(format, name);
works.
More of an idea as opposed to an answer.
For the example shown in the question, you can do the following.
var format = "URL: ";
...
var url = "http://google.com";
...
var result= $"{format} {url}";
I have an actual project where I have to do something like this a lot:
var label = "Some Label";
var value = "SomeValue";
//both label & value are results of some logic
var result = $"{label}: {value}";
You can with the right Nuget package: https://www.nuget.org/packages/InterpolatedStringFormatter
var mystring = "a thing(and something {other})";
Console.WriteLine(mystring.Interpolate("else"));
Outputs:
a thing(and something else)
It seems that you can do it like this:
var googleUrl = "http://google.com";
var url = $"URL: {googleUrl}";
System.Console.WriteLine(url);
You can check for more details in https://msdn.microsoft.com/en-us/library/dn961160.aspx

Does String.Replace() create a new string if there's nothing to replace?

For example:
public string ReplaceXYZ(string text)
{
string replacedText = text;
replacedText = replacedText.Replace("X", String.Empty);
replacedText = replacedText.Replace("Y", String.Empty);
replacedText = replacedText.Replace("Z", String.Empty);
return replacedText;
}
If I were to call "ReplaceXYZ" even for strings that do not contain "X", "Y", or "Z", would 3 new strings be created each time?
I spotted code similar to this in one of our projects. It's called repeatedly as it loops through a large collection of strings.
It does not return a new instance if there is nothing to replace:
string text1 = "hello world", text2 = text1.Replace("foo", "bar");
bool referenceEqual = object.ReferenceEquals(text1, text2);
After that code executes, referenceEqual is set to true.
Even better, this behavior is documented:
If oldValue is not found in the current instance, the method returns the current instance unchanged.
Otherwise, this would be implementation-dependent and could change in the future.
Note that there is a similar, documented optimization for calling Substring(0) on a string value:
If startIndex is equal to zero, the method returns the original string unchanged

Categories