我有一个名为hello world的字符串
我需要把"world"换成" chsharp "
我用:
string.Replace("World", "csharp");
但结果是,字符串没有被替换。原因在于区分大小写。原来的字符串包含“世界”,而我试图取代“世界”。
有没有办法避免字符串中的这种区分大小写的情况?替代方法?
我有一个名为hello world的字符串
我需要把"world"换成" chsharp "
我用:
string.Replace("World", "csharp");
但结果是,字符串没有被替换。原因在于区分大小写。原来的字符串包含“世界”,而我试图取代“世界”。
有没有办法避免字符串中的这种区分大小写的情况?替代方法?
当前回答
另一种方法是使用StringComparison选项忽略String.Replace()中的大小写敏感性。CurrentCultureIgnoreCase
string.Replace("World", "csharp", StringComparison.CurrentCultureIgnoreCase)
其他回答
使用这个,测试和100%工作!
VB。网
Dim myString As String
Dim oldValue As String
Dim newValue As String
myString = Form1.TextBox1.Text
oldValue = TextBox1.Text
newValue = TextBox2.Text
Dim working As String = myString
Dim index As Integer = working.IndexOf(oldValue, StringComparison.CurrentCultureIgnoreCase)
While index <> -1
working = working.Remove(index, oldValue.Length)
working = working.Insert(index, newValue)
index = index + newValue.Length
index = working.IndexOf(oldValue, index, StringComparison.CurrentCultureIgnoreCase)
Form1.TextBox1.Text = working
End While
为c#
private void Button2_Click(System.Object sender, System.EventArgs e)
{
string myString;
string oldValue;
string newValue;
myString = Form1.TextBox1.Text;
oldValue = TextBox1.Text;
newValue = TextBox2.Text;
string working = myString;
int index = working.IndexOf(oldValue, StringComparison.CurrentCultureIgnoreCase);
while (index != -1)
{
working = working.Remove(index, oldValue.Length);
working = working.Insert(index, newValue);
index = index + newValue.Length;
index = working.IndexOf(oldValue, index, StringComparison.CurrentCultureIgnoreCase);
Form1.TextBox1.Text = working;
}
}
我更喜欢这个- "Hello World". tolower()。Replace("world", " chsharp ");
另一种方法是使用StringComparison选项忽略String.Replace()中的大小写敏感性。CurrentCultureIgnoreCase
string.Replace("World", "csharp", StringComparison.CurrentCultureIgnoreCase)
这样不行吗?我想象不出还有什么比这更快更简单的方法了。
public static class ExtensionMethodsString
{
public static string Replace(this String thisString, string oldValue, string newValue, StringComparison stringComparison)
{
string working = thisString;
int index = working.IndexOf(oldValue, stringComparison);
while (index != -1)
{
working = working.Remove(index, oldValue.Length);
working = working.Insert(index, newValue);
index = index + newValue.Length;
index = working.IndexOf(oldValue, index, stringComparison);
}
return working;
}
}
你可以用微软。VisualBasic命名空间来查找这个帮助函数:
Replace(sourceString, "replacethis", "withthis", , , CompareMethod.Text)