Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何查找字符串并将其从字符串中删除?_C# - Fatal编程技术网

C# 如何查找字符串并将其从字符串中删除?

C# 如何查找字符串并将其从字符串中删除?,c#,C#,这里我想从字符串中删除字符串的某些部分。 我的主字符串类似于,我想从中替换这部分,我正在尝试下面的代码 string str="<grade xsi:nil=''true'' />"; string MainString="<grade xsi:nil=''true'' /><hollanderGroup xsi:nil=''true'' /><interchangeNumber xsi:nil=''true'' /><interchang

这里我想从字符串中删除字符串的某些部分。 我的主字符串类似于
,我想从中替换这部分
,我正在尝试下面的代码

string str="<grade xsi:nil=''true'' />";
string  MainString="<grade xsi:nil=''true'' /><hollanderGroup xsi:nil=''true'' /><interchangeNumber xsi:nil=''true'' /><interchangeDetails xsi:nil=''true'' /><damageCodes xsi:nil=''true'' /><damageCode1 xsi:nil=''true'' /><damageCode2 xsi:nil=''true'' />"
但是我看不到原始字符串的变化,该部分没有被删除/替换为空白。。
那么有什么解决方案吗?

如果用
替换
,您的代码运行良好,根据我们的语法,我们必须在一对
(双引号)中包含字符串,在单引号中包含字符:

string str="remove the sub-string";
string  MainString="This is the main string and I want to remove the sub-string";
string resultantString = MainString.Replace(str, " ");
Console.WriteLine(resultantString);
// will print "This is the main string and I want to" in the console
还有一件事,不需要在声明中的任何地方都使用
var
,如果您在编写代码时知道数据的类型,请使用适当的类型


或者,您也可以使用不同的方法,如Substring、Remove。在这里,我添加了一个示例,其中显示了实现相同功能的各种方法,效果很好。确保将str声明为字符串

C#
中,
's'
是一个字符,而
“s”
是一个字符串

using System;
class MainClass {
  public static void Main (string[] args) {
    string custString = "Hello World";
    string change = "World";
    Console.WriteLine(custString.Replace(change,"Me"));
  }
}

尝试使用StringBuilder对象,它可以工作

var str = "remove the sub-string";
var mainString = new StringBuilder("This is the main string and I want to remove the sub-string");
mainString.Replace(str, " ");

这就是你真正的代码吗?字符串周围有
”,“这个东西不工作”不是问题,也不是问题的描述。您知道错误、坏结果、预期结果等(相关信息)是什么。如果您希望人们帮助您,请在将来分享此信息。请参阅和。谢谢John,我之所以发布此消息,是因为它不起作用,而且仍然不起作用。@Ma6139735-John要求对问题进行更好的描述,而不是“这个东西不起作用”。写“仍然不起作用”不是更好的描述。请解释什么不起作用。我已经更新了我的问题。请看一看这是如何解释OP问题中的问题的?
var str = "remove the sub-string";
var mainString = new StringBuilder("This is the main string and I want to remove the sub-string");
mainString.Replace(str, " ");