For the following code, I can't get the string.Replace to work:
someTestString.Replace(someID.ToString(), sessionID);
when I debug and check parameters they have values I expect - i.e. someID.ToString() got "1087163075", and sessionID has "108716308" and someTestString contains "1087163075".
I have no idea why this would not work change someTestString
Complete sample:
string someTestString =
"<a href='myfoldert/108716305-1.jpg' target='_blank'>108716305-1.jpg</a>"
someTestString.Replace("108716305", "NewId42");
the result (in someTestString) should be this:
"<a href='myfoldert/NewId42-1.jpg' target='_blank'>NewId42-1.jpg</a>"
but it doesn't change. The string for someTestString remains unchanged after hitting my code.
Strings are immutable. The result of string.Replace is a new string with the replaced value.
You can either store result in new variable:
var newString = someTestString.Replace(someID.ToString(), sessionID);
or just reassign to original variable if you just want observe "string updated" behavior:
someTestString = someTestString.Replace(someID.ToString(), sessionID);
Note that this applies to all other string functions like Remove, Insert, trim and substring variants - all of them return new string as original string can't be modified.
someTestString = someTestString.Replace(someID.ToString(), sessionID);
that should work for you
strings are immutable, the replace will return a new string so you need something like
string newstring = someTestString.Replace(someID.ToString(), sessionID);
You can achieve the desired effect by using
someTestString = someTestString.Replace(someID.ToString(), sessionID);
As womp said, strings are immutable, which means their values cannot be changed without changing the entire object.
Related
For the following code, I can't get the string.Replace to work:
someTestString.Replace(someID.ToString(), sessionID);
when I debug and check parameters they have values I expect - i.e. someID.ToString() got "1087163075", and sessionID has "108716308" and someTestString contains "1087163075".
I have no idea why this would not work change someTestString
Complete sample:
string someTestString =
"<a href='myfoldert/108716305-1.jpg' target='_blank'>108716305-1.jpg</a>"
someTestString.Replace("108716305", "NewId42");
the result (in someTestString) should be this:
"<a href='myfoldert/NewId42-1.jpg' target='_blank'>NewId42-1.jpg</a>"
but it doesn't change. The string for someTestString remains unchanged after hitting my code.
Strings are immutable. The result of string.Replace is a new string with the replaced value.
You can either store result in new variable:
var newString = someTestString.Replace(someID.ToString(), sessionID);
or just reassign to original variable if you just want observe "string updated" behavior:
someTestString = someTestString.Replace(someID.ToString(), sessionID);
Note that this applies to all other string functions like Remove, Insert, trim and substring variants - all of them return new string as original string can't be modified.
someTestString = someTestString.Replace(someID.ToString(), sessionID);
that should work for you
strings are immutable, the replace will return a new string so you need something like
string newstring = someTestString.Replace(someID.ToString(), sessionID);
You can achieve the desired effect by using
someTestString = someTestString.Replace(someID.ToString(), sessionID);
As womp said, strings are immutable, which means their values cannot be changed without changing the entire object.
the interpolated string is easy, just a string lead with $ sign. But what if the string template is coming from outside of your code. For example assume you have a XML file containing following line:
<filePath from="C:\data\settle{date}.csv" to="D:\data\settle{date}.csv"/>
Then you can use LINQ to XML read the content of the attributes in.
//assume the ele is the node <filePath></filePath>
string pathFrom = ele.Attribute("from").value;
string pathTo = ele.Attibute("to").value;
string date = DateTime.Today.ToString("MMddyyyy");
Now how can I inject the date into the pathFrom variable and pathTo variable?
If I have the control of the string itself, things are easy. I can just do var xxx=$"C:\data\settle{date}.csv";But now, what I have is only the variable that I know contains the placeholder date
String interpolation is a compiler feature, so it cannot be used at runtime. This should be clear from the fact that the names of the variables in the scope will in general not be availabe at runtime.
So you will have to roll your own replacement mechanism. It depends on your exact requirements what is best here.
If you only have one (or very few replacements), just do
output = input.Replace("{date}", date);
If the possible replacements are a long list, it might be better to use
output = Regex.Replace(input, #"\{\w+?\}",
match => GetValue(match.Value));
with
string GetValue(string variable)
{
switch (variable)
{
case "{date}":
return DateTime.Today.ToString("MMddyyyy");
default:
return "";
}
}
If you can get an IDictionary<string, string> mapping variable names to values you may simplify this to
output = Regex.Replace(input, #"\{\w+?\}",
match => replacements[match.Value.Substring(1, match.Value.Length-2)]);
You can't directly; the compiler turns your:
string world = "world";
var hw = $"Hello {world}"
Into something like:
string world = "world";
var hw = string.Format("Hello {0}", world);
(It chooses concat, format or formattablestring depending on the situation)
You could engage in a similar process yourself, by replacing "{date" with "{0" and putting the date as the second argument to a string format, etc.
SOLUTION 1:
If you have the ability to change something on xml template change {date} to {0}.
<filePath from="C:\data\settle{0}.csv" to="D:\data\settle{0}.csv" />
Then you can set the value of that like this.
var elementString = string.Format(element.ToString(), DateTime.Now.ToString("MMddyyyy"));
Output: <filePath from="C:\data\settle08092020.csv" to="D:\data\settle08092020.csv" />
SOLUTION 2:
If you can't change the xml template, then this might be my personal course to go.
<filePath from="C:\data\settle{date}.csv" to="D:\data\settle{date}.csv" />
Set the placeholder like this.
element.Attribute("to").Value = element.Attribute("to").Value.Replace("{date}", DateTime.Now.ToString("MMddyyyy"));
element.Attribute("from").Value = element.Attribute("from").Value.Replace("{date}", DateTime.Now.ToString("MMddyyyy"));
Output: <filePath from="C:\data\settle08092020.csv" to="D:\data\settle08092020.csv" />
I hope it helps. Kind regards.
If you treat your original string as a user-input string (or anything that is not processed by the compiler to replace the placeholder, then the question is simple - just use String.Replace() to replace the placehoder {date}, with the value of the date as you wish. Now the followup question is: are you sure that the compiler is not substituting it during compile time, and leaving it untouched for handling at the runtime?
String interpolation allows the developer to combine variables and text to form a string.
Example
Two int variables are created: foo and bar.
int foo = 34;
int bar = 42;
string resultString = $"The foo is {foo}, and the bar is {bar}.";
Console.WriteLine(resultString);
Output:
The foo is 34, and the bar is 42.
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.
I would like to transforme this string '" into this string >>.
I have already read this thread.
Here is what I've tried:
string str = "'"";
str = str.Replace("'\"",">>");
It is not throwing any error but doesn't do anything neither. Thank you very much.
string.Replace returns a new string since strings are immutable in C#.
Simply do str = str.Replace("'\"",">>");
Inserting a string into a string doesn't appear to have any effect. I'm using the following code:
string stNum = string.Format("{0:00}", iValue);
DesiredCode.Insert(0, stNum);
txtCode.Text = DesiredCode;
Breakpoints show stNum has the desired value, and DesiredCode is also as we would expect before insertion.
But after insertion, nothing will happen and the DesiredCode is the same as before!
Can someone please point me in the right direction as to what I'm doing wrong?
Strings are immutable. All the methods like Replace and Insert return a new string which is the result of the operation, rather than changing the data in the existing string. So you probably want:
txtCode.Text = DesiredCode.Insert(0, stNum);
Or for the whole block, using direct ToString formatting instead of using string.Format:
txtCode.Text = DesiredCode.Insert(0, iValue.ToString("00"));
Or even clearer, in my opinion, would be to use string concatenation:
txtCode.Text = iValue.ToString("00") + DesiredCode;
Note that none of these will change the value of DesiredCode. If you want to do that, you'd need to assign back to it, e.g.
DesiredCode = iValue.ToString("00") + DesiredCode;
txtCode.Text = DesiredCode;
Strings are immutable!
DesiredCode = DesiredCode.Insert(0, stNum);
Strings are immutable in C#. What this means is that you need to assign the return value of String.Insert to a string variable after the operation in order to access it.
string stNum = string.Format("{0:00}", iValue);
DesiredCode = DesiredCode.Insert(0, stNum);
txtCode.Text = DesiredCode;