简体   繁体   English

String.Replace无法正常工作

[英]String.Replace not working as expected

I have the following problem with String.Replace: 我在String.Replace中遇到以下问题:

string str = "0˄0";
str = str.Replace("˄", "&&");

when I print out str, it will be "0&0" instead of "0&&0". 当我打印出str时,它将是“ 0&0”而不是“ 0 && 0”。 To get "0&&0", I have to write 要得到“ 0 && 0”,我必须写

str = str.Replace("˄", "&&&&");

Why is that? 这是为什么?

& is a special character in WinForms, used to indicate keyboard shortcuts. &是WinForms中的特殊字符,用于指示键盘快捷键。 Using && is how WinForms escapes the & symbol. WinForms如何使用&&来转义&符号。

So, to display it in WinForms you are necessarily going to have to place two & characters in your string as you have here: 因此,要在WinForms中显示它,您必须像在此处那样在字符串中放置两个 &字符:

str = str.Replace("˄", "&&&&");

This is strictly a WinForms "thing" and has nothing to do with a C# or .NET string escaping specifically. 严格来说,这是WinForms的“东西”,与专门转义的C#或.NET字符串无关。 It has been this way at least as far back as Visual Basic 4 - probably before then. 这种方式至少可以追溯到Visual Basic 4 -大概在此之前。

You may want to check out this post: http://moiashvin-tech.blogspot.com/2008/05/escape-ampersand-character-in-c.html 您可能想查看一下此帖子: http : //moiashvin-tech.blogspot.com/2008/05/escape-ampersand-character-in-c.html

Labels are handled differently in WinForms. 在WinForms中,标签的处理方式有所不同。 You should be able to do as the post suggests and set the UseMnemonic property to false, see if that works. 您应该能够按照帖子中的建议进行操作,并将UseMnemonic属性设置为false,看看是否可行。

The answer is in the first comment - '&' is a special character for WinForms (and the underlying Win32 API) which is/was used to indicate a shortcut character for menu/dialog items. 答案在第一条注释中-“&”是WinForms(和基础的Win32 API)的特殊字符,用于/曾经指示菜单/对话框项的快捷方式字符。

'&' in strings means nothing special to C#, but if you want to put it on a form/dialog label, then you need to escape the '&' by adding another one in front. 字符串中的“&”对C#而言并没有什么特别的含义,但是,如果您想将其放在表单/对话框标签上,则需要在前面加上另一个来转义“&”。

Personally, I would get the string how I really wanted it in my 'business logic' first, then escape the '&' characters as part of displaying the string on the form. 就个人而言,我会首先在“业务逻辑”中获得真正想要的字符串,然后转义“&”字符作为在表单上显示字符串的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM