Hi,
I am trying to change only part of a string with a new value. I have a string with the value "Hello". I want to change it to "Heslo". I am trying to do this:
string sal = "Hello";
sal.substring(2, 1) = "s";
This keeps giving me an error "The left hand side of the assigner should be a variable, property, or indexer"
How can I accomplish this in C#
thanks

Modfying Part of a String
steveharper
you don't have to change your app to VB. Everything you can acheive using VB you can do it in C# but it might take more lines of code. PS the function you just used was added to VB.Net just for compatibility with VB6.0.
shivaraj
It's just a variation of the earlier reply:
sal = sal.Substring(0, 2) + "s" + sal.Substring(2);
David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB to C# converter
Instant VB: C# to VB converter
Instant C++: C# to C++ converter and VB to C++ converter
Instant J#: VB to J# converter
Clear VB: Cleans up VB.NET code
Clear C#: Cleans up C# code
MaTT_17
Hawkeye7,
Your second line of code equates to:
which causes the error you got because you attempted to assign a value to a literal.
Arnie's answer works well, but it adds a slight amount of overhead. You should consider using System.Text.StringBuilder if your application manipulates many strings. Here's how it works in your example:
string sal = "Hello"; StringBuilder sb = new StringBuilder(sal); sb.Replace('l', 's', 2, 1); sal = sb.ToString();Strings in .Net are immutable—once you create one, you can't change it. Adding strings as in
"Hello" + " there"doesn't put the two strings side-by-side in memory. Instead, it creates a third string, and this bit of overhead multiplies in code that manipulates many strings—especially in loops.I hope this helps.
grybyx
Fairy
sal = sal.Substring(0, 2) +
"s" + sal.Substring(3, 2);Not sophisticated, but it works.
Arnie
photek
Mid(String, 3, 1) = "s"
in C#
Dmitry Vasilevsky MSFT
I just moved the app to VB and did
Mid(String, 3, 1) = "s"
which worked
The actual string is 1200 characters long and I needed this functionality. I guess there are some things that you cannot do in C#
thanks for your help
DanielHillier
thanks,
sal = sal.Remove(2, 1).Insert(2, "s");
does what I needed.
GJCreme
Alternatively, the following slightly more concise version is produced by our Instant C# VB to C# converter:
sal = sal.Remove(2, 1).Insert(2, "s");
David Anton
www.tangiblesoftwaresolutions.com
Instant C#: VB to C# Converter
Instant VB: C# to VB Converter
Instant C++: C# to C++ and VB to C++ Converter
Instant J#: VB to J# Converter
Clear VB: Cleans up VB code
Clear C#: Cleans up C# code