Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

change string element? 3

Status
Not open for further replies.

ajikoe

Programmer
Apr 16, 2004
71
0
0
ID
Hello,
I have the string variabel and I want to change value in specific position. How can I do that?
string mystr ="Hello World";

I want to change mystr into : "Heldo World"
But I fail to make this:
mystr[3]="d"; //Fail

Thanks
Pujo
 
An indexer is a member that enables an object to be indexed in the same way as an array. Whereas properties enable field-like access, indexers enable array-like access.
The string class has one but it is read only e.q you only access the value at a given index but you cannot replace it using the indexer property.
Use one form of the Replace() function or combine it with IndexOf()/ IndexOfAny () to find a sepcific occurence of the char/string to replace.
-obislavu-
 
Unfortunately, there doesn't seem to be a one-statement way to do this in .NET, but here's what I do:

mystr = mystr.Remove(3, 1);
mystr = mystr.Insert(3, "d");

Or, one line: mystr = mystr.Remove(3,1).Insert(3, "d");

 
strings in c# are immutable - which means that once set their values are constant.

If you append data to a string - in fact you are binning the old string and creating a new one - which is memory inefficient.

You should use the StringBuilder class if you are dealing with a string value that may change - and then commit to string when you need to.

M.

Hollingside Technologies, Making Technology work for you.
 
In practice, using regular strings is actually very efficient when the strings are small. I write a few very intensive string manipulation apps and using StringBuilder only boosts their performance when accumulating or adding on to very large strings.

For example, if you're parsing through a file a line at a time and manipulating one line at a time very intensively, you won't notice any performance boost with StringBuilder. You'll only notice better performance if you're accumulating those manipulated line into one string or manipulating the entire file as a single string.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top