473,386 Members | 1,997 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

String.Replace method not usable when knowing index to replace

Hi,

Just want to replace character at index 1 of a string with another
character. Just want to replace character at that position. I thought
Replace method would be overloaded with an index parameter with which
you can write wanted character at that position. But no, Replace
method only allows replacing one known character with another. The
problem is I don't know the character to replace, just must replace
the character at a known index.

This is the first workaround I've found:

string s = "ihj";
s = s.Remove(1, 1).Insert(1, "p");

And here is the second one:

string s = "ihj";
char[] array = s.ToCharArray();
array[1] = 'p';
s = new string(array);

A bit complicated,, don't you think? I think String.Replace should be
overloaded with something like this:

string Replace (int index, char newCharacter);

Any comments?

Thanks in advance.

Oct 17 '07 #1
10 18593
"Lonifasiko" <ml*******@gmail.comwrote:
Just want to replace character at index 1 of a
string with another character.
Use StringBuilder instead of string.

Eq.
Oct 17 '07 #2
Lonifasiko wrote:
Hi,

Just want to replace character at index 1 of a string with another
character. Just want to replace character at that position. I thought
Replace method would be overloaded with an index parameter with which
you can write wanted character at that position. But no, Replace
method only allows replacing one known character with another. The
problem is I don't know the character to replace, just must replace
the character at a known index.

This is the first workaround I've found:

string s = "ihj";
s = s.Remove(1, 1).Insert(1, "p");

And here is the second one:

string s = "ihj";
char[] array = s.ToCharArray();
array[1] = 'p';
s = new string(array);

A bit complicated,, don't you think? I think String.Replace should be
overloaded with something like this:

string Replace (int index, char newCharacter);

Any comments?

Thanks in advance.
The problem is that it's not that easy. Strings are immutable, so you
always have to create a new string when you are changing it, you can't
change an existing string.

I think that when you change characters in a string in that manner, you
usually change more than one character, so a method in the string class
would not be very useful. It would rather be misleading, causing people
to inadvertently create a lot of intermediate strings without realising it.

Here is another way of doing it:

StringBuilder builder = new StringBuilder(s);
builder.Chars[1] = 'p';
s = builder.ToString();

The StringBuilder uses a mutable string internally. When you call
ToString you will get that string as a regular immutable string, so
there is no extra intermediate string or array created as with the other
methods you presented.

--
Göran Andersson
_____
http://www.guffa.com
Oct 17 '07 #3
StringBuilder offers Replace method overload, but still forces me to
know which character I want to replace. See MSDN help:

- StringBuilder.Replace (Char, Char, Int32, Int32) Replaces, within a
substring of this instance, all occurrences of a specified character
with another specified character.

- StringBuilder.Replace (String, String, Int32, Int32) Replaces,
within a substring of this instance, all occurrences of a specified
string with another specified string.

The problem is I don't know which is the character that must be
replaced; I only know its position! I've tried both these methods
passing null, String.Empty and so on as the first parameter, but
crashes during execution.

StringBuilder sb = new StringBuilder("ihj");
sb = sb.Replace(null, "p", 1, 1); // Cannot specify "h" must be
changed cause character at position 1 it's not always "h"

Any other ideas?

Regards.

Oct 17 '07 #4
Sorry, did not read Göran's previous post ;-)

Ok, then another workaround would be:

StringBuilder sb = new StringBuilder("ihj");
sb[1] = 'p';

I think it's still a bit rudimentary, but well, I see there's nothing
more to do......

Thanks.

Oct 17 '07 #5
On Wed, 17 Oct 2007 01:50:16 -0700, Lonifasiko <ml*******@gmail.com>
wrote:
>Hi,

Just want to replace character at index 1 of a string with another
character. Just want to replace character at that position. I thought
Replace method would be overloaded with an index parameter with which
you can write wanted character at that position. But no, Replace
method only allows replacing one known character with another. The
problem is I don't know the character to replace, just must replace
the character at a known index.

This is the first workaround I've found:

string s = "ihj";
s = s.Remove(1, 1).Insert(1, "p");

And here is the second one:

string s = "ihj";
char[] array = s.ToCharArray();
array[1] = 'p';
s = new string(array);

A bit complicated,, don't you think? I think String.Replace should be
overloaded with something like this:

string Replace (int index, char newCharacter);

Any comments?

Thanks in advance.
A String.Replace() as you ask for makes strings mutable, which will
break a number of design assumptions in many programs. If a string
changes, then all other references to that string will now reference
to changed string, not the original one. This effectively turns all
strings into volatile declarations.

Having given the warning, what you want can be done in unsafe code by
using a char pointer:
public static unsafe void ChangeStringChar(string text, int index,
char newChar) {
if (index < 0 || index >= text.Length) {
throw new IndexOutOfRangeException();
}
fixed (char* cp = text) {
cp[index] = newChar;
}
}

public static void Main() {

string oldText = "12345";
string secondRef = oldText;

Console.WriteLine("Old text before = {0}", oldText);
Console.WriteLine("Second ref before = {0}", oldText);

ChangeStringChar(oldText, 1, 'X');

Console.WriteLine("Old text after = {0}", oldText);
Console.WriteLine("Second ref after = {0}", oldText);
}

Notice how the second reference to the original text is also changed.
If you don't want this side-effect then avoid this method and use one
of the other methods suggested. The code is marked unsafe for a good
reason.

rossum

Oct 17 '07 #6
"Lonifasiko" <ml*******@gmail.comwrote in message
news:11*********************@i13g2000prf.googlegro ups.com...
Sorry, did not read Göran's previous post ;-)

Ok, then another workaround would be:

StringBuilder sb = new StringBuilder("ihj");
sb[1] = 'p';

I think it's still a bit rudimentary, but well, I see there's nothing
more to do......

Why do you think it is " a bit rudimentary"?
It seems perfectly logical.
Is the complaint that you had to convert to a StringBuilder first?
Or are you upset that the String class doesn't support this?

Just curious
Bill

Oct 17 '07 #7
A string build uses an array internally as there is no such thing as a
muttable string .net. the ToString method returns a new string created from
that array.
--
Ciaran O''Donnell
http://wannabedeveloper.spaces.live.com
"Göran Andersson" wrote:
Lonifasiko wrote:
Hi,

Just want to replace character at index 1 of a string with another
character. Just want to replace character at that position. I thought
Replace method would be overloaded with an index parameter with which
you can write wanted character at that position. But no, Replace
method only allows replacing one known character with another. The
problem is I don't know the character to replace, just must replace
the character at a known index.

This is the first workaround I've found:

string s = "ihj";
s = s.Remove(1, 1).Insert(1, "p");

And here is the second one:

string s = "ihj";
char[] array = s.ToCharArray();
array[1] = 'p';
s = new string(array);

A bit complicated,, don't you think? I think String.Replace should be
overloaded with something like this:

string Replace (int index, char newCharacter);

Any comments?

Thanks in advance.

The problem is that it's not that easy. Strings are immutable, so you
always have to create a new string when you are changing it, you can't
change an existing string.

I think that when you change characters in a string in that manner, you
usually change more than one character, so a method in the string class
would not be very useful. It would rather be misleading, causing people
to inadvertently create a lot of intermediate strings without realising it.

Here is another way of doing it:

StringBuilder builder = new StringBuilder(s);
builder.Chars[1] = 'p';
s = builder.ToString();

The StringBuilder uses a mutable string internally. When you call
ToString you will get that string as a regular immutable string, so
there is no extra intermediate string or array created as with the other
methods you presented.

--
Göran Andersson
_____
http://www.guffa.com
Oct 17 '07 #8
Göran is correct; it is a private string (m_StringValue). It breaks a
fair few rules, but it gets away with it on the grounds that it never
lets you see the string that it is abusing.

However, this is entirely an implementation detail, and may change
between framework versions. The behavior is the same, though.

The point is that non-core code should never see a mutable string.

Marc
Oct 17 '07 #9
Ciaran O''Donnell wrote:
A string build uses an array internally as there is no such thing as a
muttable string .net. the ToString method returns a new string created from
that array.
No, it does not.

Download a copy of .NET Reflector, and have a look at the code yourself.

--
Göran Andersson
_____
http://www.guffa.com
Oct 17 '07 #10
rossum wrote:
>string Replace (int index, char newCharacter);
[...]
A String.Replace() as you ask for makes strings mutable, which will
break a number of design assumptions in many programs. If a string
No it doesn't. Existing versions of Replace work in this exact same way
-- they take the parameters, using them they create a new string, which
is then returned as the method's return value.

Converting the string to a character array and modifying the particular
index in the array seems the sensible way to solve this to me...

Chris.
Oct 17 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

20
by: hagai26 | last post by:
I am looking for the best and efficient way to replace the first word in a str, like this: "aa to become" -> "/aa/ to become" I know I can use spilt and than join them but I can also use regular...
32
by: tshad | last post by:
Can you do a search for more that one string in another string? Something like: someString.IndexOf("something1","something2","something3",0) or would you have to do something like: if...
6
by: localhost | last post by:
I have a string that looks like this: "document.form1.textBox1.focus ();document.form1.textBox1.select();" I want to replace the text between "document.form1." and ".focus()", as well as...
2
by: Digital Fart | last post by:
following code would split a string "a != b" into 2 strings "a" and "b". but is there a way to know what seperator was used? string charSeparators = { "=", ">=", "<=" , "!=" }; string s1 =...
4
by: Sjaakie | last post by:
I need to replace parts of a string, in a collection deserialized from an XML file, with values from another collection. Is there another, more clever/faster/better, method than the loops below? ...
122
by: C.L. | last post by:
I was looking for a function or method that would return the index to the first matching element in a list. Coming from a C++ STL background, I thought it might be called "find". My first stop was...
4
by: Michael Yanowitz | last post by:
Hello: If I have a long string (such as a Python file). I search for a sub-string in that string and find it. Is there a way to determine if that found sub-string is inside single-quotes or...
21
by: phpCodeHead | last post by:
Code which should allow my constructor to accept arguments: <?php class Person { function __construct($name) { $this->name = $name; } function getName()
9
by: ma | last post by:
Hello, I want to change one character in a string to a new character. How can i do this. For example I have a string called x and it contains "This is a test" and I want to change the i in is to a...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.