C#有效的方法来为字符串中的某些字符添加逃生
需要用\
加上原始字符替换字符串中的
charachter
string origin = "words&sales -test\strange";
string[] specialChars = new string[]{"\", "&", "-", "?",......};
我
"words\&sales \-test\\strange"
一些 并更换
感谢
i need to replace some charachters in a string with a \
plus the original character
so giving thats string and array
string origin = "words&sales -test\strange";
string[] specialChars = new string[]{"\", "&", "-", "?",......};
i want to get
"words\&sales \-test\\strange"
notice that the \
itself is a character to find and replace
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般而言,即使您正在转换另一个
string
value,c#/。net中构建字符串
值的最快方法即使。另一个问题是确定应逃脱的“最佳”方法:如果在编译时固定了可逃逸的字符集,则使用
switch()
语句,因为将被编译到本机跳台上,该台式比使用运行时hashset< char>
用于确定设置成员:例如:
如果在运行时定义了一组可逃逸的字符,则使用<代码> hashset&lt; char&gt; 可能是最佳的总体选项 - 尽管如果您知道自己只是在有限范围内使用Unicode代码点处理字符(例如,在范围内与ASCII兼容的字符
0x00到0x7f
)然后,您可以使用boolean [127]
数组来存储逃生标志映射。使用
hashset&lt; char&gt;
,就是这样:当然,可以进一步优化上述代码:一些建议:
String> String> String Input
什至甚至首先有任何可逃避的字符:如果其字符都不是逃脱的,则只需直接返回input
而不会创建新的StringBuilder
。StringBuilder
实例的(按需)池,而不是在每个呼叫上创建新实例。readonlyspan&lt; char&gt;
而不是字符串
用于输入和写入输出到span&lt; char&gt;
- 您需要一个初始步骤来计算首先,span&lt; char&gt;
首先需要的最小尺寸,然后将该信息传递回呼叫者。能力:
stringbuilder
而不是我的(懒惰)25%估算值。Input
值键键入。Generally speaking, the fastest way to build
String
values in C#/.NET is with aStringBuilder
, even if you're transforming anotherString
value.The other problem is the "best" way to determine which char values should be escaped or not: if the set of escapable characters is fixed at compile-time, then use a
switch()
statement, as that will be compiled to a native jump-table, which is faster than using a runtimeHashSet<Char>
for determining set-membership:e.g.:
If the set of escapable character is defined at runtime then using a
HashSet<Char>
will likely be the best overall option - though if you know you're only processing chars with Unicode code-points within a limited range (say ASCII-compatible chars in the range0x00 to 0x7F
) then you could use aBoolean[127]
array to store the escape flag map.Using a
HashSet<Char>
, it would be like this:Of course, the above code can be optimized further: some suggestions:
String input
even has any escapable characters in the first place: if none of its characters are escapable then just returninput
directly without having created a newStringBuilder
.StringBuilder
instances instead of creating new instances on every call.ReadOnlySpan<Char>
instead ofString
for input and writing output toSpan<Char>
- you'll need an initial step to calculate the required minimum size of theSpan<Char>
first though, and pass that info back to the caller.capacity:
value for theStringBuilder
instead of my (lazy) 25% estimate.input
value.