Replace method in C# not working for individual character?
I've bee开发者_运维百科n looking around and it seems like I'm using this properly, but the results are failing. I want to go through and get rid of any 0's and replace them with o's.
newString = strOld.Replace('0', 'o'); // doesn't work.
newString = strOld.Replace("0", "o"); // doesn't work either.
Am I doing something wrong?
I made this test, and it works fine:
class Program
{
static void Main(string[] args)
{
var newString = "M0000".Replace('0', 'o');
}
}
Try a small test case, similar to the one I created, and see what happens.
Turns out in order to use the replace method it had to go into the same string. So while this won't work:
String newString;
String oldString = "b00k";
newString = oldString.Replace('0', 'o');
This will work:
String newString = "b00k";
newString = newString.Replace('0', 'o');
Appreciate all the feedback.
I was facing the same problem, actually just for information, I was doing something thing like myOldString.Replace("#", "No.");
.
It was not working, I checked it.
Finally I found the solution, when i replaced the above string as
myOldString = myOldString.Replace("#","No");
string.replace makes a replica, earlier i was not assigning that to the actual string.
Make sure you are not making such t
Works fine here... the char version should work regardless of case if they were letters (I assume you're trying to replace zeroes with an lowercase O). Are you maybe using a font that does not distinguish between zero and the letter O or something like that?
You're not doing anything wrong. If you want to do a character replace instead of a string replace you need to do: s.Replace(char.Parse("0"), char.Parse("o"))
, but I can't think of any reason your code doesn't work.
The following link shows this very clearly: http://www.dotnetperls.com/replace If you use string.Replace, it has to be assigned (as mentioned above by Geeklat):
String newString = "b00k";
newString = newString.Replace('0', 'o');
If you use "StringBuilder" the variable not have to be assigned - Here is a Sample Program (Output is below):
using System;
using System.Text;
class Program
{
static void Main()
{
const string s = "This is an example.";
// A
// Create new StringBuilder from string
StringBuilder b = new StringBuilder(s);
Console.WriteLine(b);
// B
// Replace the first word
// The result doesn't need assignment
b.Replace("This", "Here");
Console.WriteLine(b);
// C
// Insert the string at the beginning
b.Insert(0, "Sentence: ");
Console.WriteLine(b);
}
}
Output:
This is an example.
Here is an example.
Sentence: Here is an example.
精彩评论