//Sentence has quotes
string nameSentence = "Take my name \"Wesley\" out of quotes";
//Get the index before the quotes`enter code here`
int begin = nameSentence.LastIndexOf("name") + "name".Length;
//Get the index after the quotes
int end = nameSentence.LastIndexOf("out");
//Get the part of the string with its quotes
string name = nameSentence.Substring(begin, end - begin);
//Remove its quotes
string newName = name.Replace("\"", "");
//Replace new name (without quotes) within original sentence
string updatedNameSentence = nameSentence.Replace(name, newName);
//Returns "Take my name Wesley out of quotes"
return updatedNameSentence;
如果你只想从字符串的两端(而不是中间)去掉引号,并且有可能在字符串的两端都有空格(例如,解析一个 CSV 格式的文件,其中在逗号后面有一个空格) ,那么你需要调用 Trim 函数 两次... 例如:
string myStr = " \"sometext\""; //(notice the leading space)
myStr = myStr.Trim('"'); //(would leave the first quote: "sometext)
myStr = myStr.Trim().Trim('"'); //(would get what you want: sometext)
如果你想删除一个字符,我猜它更容易简单地读数组,跳过字符,返回数组。我在定制解析 vcard 的 json 时使用它。
因为它是带有“引用”文本标识符的 bad json。
将下面的方法添加到包含扩展方法的类中。
public static string Remove(this string text, char character)
{
var sb = new StringBuilder();
foreach (char c in text)
{
if (c != character)
sb.Append(c);
}
return sb.ToString();
}