如何从句子的特定单词中删除特殊字符 [英] How can I remove special characters from a specific word of a sentence
本文介绍了如何从句子的特定单词中删除特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何能够从句子中的单词中删除像撇号这样的特殊字符,例如
而不是----- Hello'big'world < br $> b $ b
我希望它是----------你好大世界
< b>我尝试了什么:
尝试附上这样的字眼
How will i be able to remove special character like apostrophe from a word in a sentence like
instead of ----- Hello 'big' world
I want it to be ---------- Hello big world
What I have tried:
tried appending the words like this
StringBuilder sb = new StringBuilder();
foreach (char c in strMyString) {
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') | || (c >= 'a' && c <= 'z') ) {
sb.Append(c);
}
}
return sb.ToString();
}
推荐答案
private readonly char[] validCharacters
= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890- ".ToCharArray();
public string StripCharacters(string input, char[] validChars)
{
return input.ToCharArray()
.Where(c => validChars.Contains(c))
.Aggregate(new StringBuilder(), (current, next)
=> current.Append(next), sb => sb.ToString());
}
使用:
To use:
var cleaned = StripCharacters("instead of ----- Hello 'big' world", validCharacters);
输出:
Outputs:
instead of ----- Hello big world
这使您可以更好地控制要保留的字符以及要删除的字符。
This gives you greater control over which characters to keep, and which to strip.
使用正则表达式:
Use a Regex:
public static Regex removeSpecials = new Regex(
"[^\w\s-]",
RegexOptions.CultureInvariant
| RegexOptions.Compiled
);
...
string result = removeSpecials.Replace(InputText,"");
空格和连字符添加,0-9a-zA-Z替换为\w - OriginalGriff [/ edit]
[edit]Space and hyphen added, 0-9a-zA-Z replaces with \w - OriginalGriff[/edit]
首先看,你忘了在过滤中允许空格if
。
On first look, you forgot to allow spaces in the filteringif
.
(c == ' ')
这篇关于如何从句子的特定单词中删除特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文