String Insertion won't take any effect - c#

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;

Related

How to change text dynamic in unity

at line 161,I want to insert my text in parameter t,but it won't change when i debug it.although the parameter tmp had alredy changed.
I want to change this Text in UI,when my parameter t changes.
With respect to your specific issue, Insert is defined as:
public string Insert (int startIndex, string value);
and returns a new string. In C#, strings aren't modified, new strings are created. In this way, they act like a value type, even though they're a reference type. In other words, once a string is created, it is never modified - it's 'immutable'. So, you need to store your newly created string.
In cases like this, I like to use the string interpolation, as it allows me to get a slightly clearer representation of what the final string will look like.
var tmp = System.Text.Encoding.UTF8.GetString ( e.Message );
t.text = $"{tmp}\n{t.text}"; // Note that a newline is represented as \n
Or, if you add the System.Text namespace; you could reduce it down to:
using System.Text;
...
t.text = $"{Encoding.UTF8.GetString ( e.Message )}\n{t.text}";
The string type in c# is immutable, therefore Insert returns a new string instead of modifying the current one.
Do:
t = t.text.Insert(0, tmp + "//n");
See also
How to modify string contents in C#

How can i modify a string in C# by replacing text? [duplicate]

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.

Replace string with \ not work in visual studio 2019 [duplicate]

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.

Convert string array value to int when empty string value is possible

I am having trouble converting a value in a string array to int since the value could possibly be null.
StreamReader reader = File.OpenText(filePath);
string currentLine = reader.ReadLine();
string[] splitLine = currentLine.Split(new char[] { '|' });
object.intValue = Convert.ToInt32(splitLine[10]);
This works great except for when splitLine[10] is null.
An error is thrown: `System.FormatException: Input string was not in a correct format.
Can someone provide me with some advice as to what the best approach in handling this would be?
Don't use convert, it is better to use
int.TryParse()
e.g.
int val = 0;
if (int.TryParse(splitLine[10], out val))
obj.intValue = val;
You can use a TryParse method:
int value;
if(Int32.TryParse(splitLine[10], out value))
{
object.intValue = value;
}
else
{
// Do something with incorrect parse value
}
if (splitLine[10] != null)
object.intValue = Convert.ToInt32(splitLine[10]);
else
//do something else, if you want
You might also want to check that splitLine.Length > 10 before getting splitLine[10].
If you're reading something like a CSV file, and there's a chance it could be somewhat complicated, such as reading multiple values, it probably will make sense for you to use a connection string or other library-sorta-thing to read your file. Get example connection strings from http://www.connectionstrings.com/textfile, using Delimited(|) to specify your delimiter, and then use them like using (var conn = new OleDbConnection(connectionString)). See the section in http://www.codeproject.com/Articles/27802/Using-OleDb-to-Import-Text-Files-tab-CSV-custom about using the Jet engine.
I would go with
object.intValue = int.Parse(splitLine[10] ?? "<int value you want>");
if you're looking for the least code to write, try
object.intValue = Convert.ToInt32(splitLine[10] ?? "0");
If you want to preserve the meaning of the null in splitLine[10], then you will need to change the type of intValue to be of type Nullable<Int32>, and then you can assign null to it. That's going to represent a lot more work, but that is the best way to use null values with value types like integers, regardless of how you get them.

How to Use substring in c#?

I have -$2.00 as the string. I am trying to change it to decimal by removing - and $ using substring, but I am doing it wrong. Can someone help me?
Thanks.
string m = "-$2.00";
decimal d = Math.Abs(Decimal.Parse(m, NumberStyles.Currency));
Substring will return a new string. I suspect your issue is likely from trying to mutate the string in place, which does not work.
You can do:
string result = original.Substring(2);
decimal value = decimal.Parse(result);
Depending on how the input string is generated, you may want to use decimal.TryParse instead, or some other routine with better error handling.
Don't.
Instead, you should make .Net do the dirty work for you:
Decimal value = Decimal.Parse("-$2.00", NumberStyles.Currency);
If, for some reason, you don't want a negative number, call Math.Abs.
All string operations return a new string, because string is immutable
I wouldn't use substring if you can avoid it. It would be much simpler to do something like:
string result = original.Replace("$", "").Replace("-", "");

Categories