且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在字符串中设置字符

更新时间:2023-11-15 16:27:04

我更喜欢蒙面文本框 [ ^ ],然后你将在这里获得正确格式化的字符串。


绝对不可能修改任何字符串。字符串是不可变的。所有修改字符串的方法实际上都是使用源字符串中的数据创建一个全新的字符串。



您可以使用可变类 System.Text.StringBuilder http://msdn.microsoft.com/en-us/library/system.text.stringbuilder%28v=vs.110%29.aspx [ ^ ]。



最后,您仍然可以通过调用实例方法 StringBuilder.ToString()(重写 System.Object.ToString())。但是你应该明白它会生成一个全新的字符串。

但是,要了解字符串是如何工作的,请阅读字符串实习

http://msdn.microsoft.com/en-us /library/system.string.intern(v=vs.110).aspx [ ^ ],

http://msdn.microsoft.com/en-us/library/system.string.isinterned(v = vs.110) .aspx [ ^ ],

http://en.wikipedia.org/ wiki / String_interning [ ^ ],

http://csharpexperiments.blogspot.com/2013/04/ string-interning.html [ ^ ]。



-SA


如果解决方案2不是一个选项,你可以仍然会使用正则表达式来提取初始字符串的三个部分,允许你在它们之间放置减号。



这应该是这样的:

 使用 System.Text.RegularExpressions; 

public static string GetFormattedValue( string initial){
string formatRegex = @ ^(?< First> [\d] {7})(?< Second> [\d] {4} )(小于?第三&GT; [\d] {3})

I set "-" in string how can i do it?

For example, 02700060024112 is string
then i store in database string as "0270006-0024-112"

how can i do???

I'd prefer a Masked Textbox[^] on the Windows Form where the data are entered, then you'll get the string formatted correctly already here.


It is absolutely impossible to modify any string. Strings are immutable. All methods which "modify" a string actually create a brand new string using the data from source string(s).

You can use the mutable class System.Text.StringBuilder: http://msdn.microsoft.com/en-us/library/system.text.stringbuilder%28v=vs.110%29.aspx[^].

At the end, you still can back to a string, by calling the instance method StringBuilder.ToString() (overridden System.Object.ToString()). But you should understand that it will generate a brand new string.
However, to understand how strings really work, read about string interning:
http://msdn.microsoft.com/en-us/library/system.string.intern(v=vs.110).aspx[^],
http://msdn.microsoft.com/en-us/library/system.string.isinterned(v=vs.110).aspx[^],
http://en.wikipedia.org/wiki/String_interning[^],
http://csharpexperiments.blogspot.com/2013/04/string-interning.html[^].

—SA


If solution 2 is not an option, you can still go for a regular expression that will extract the three parts of your initial string, allowing you to place your minus sign between them.

This should look like:
using System.Text.RegularExpressions;

public static string GetFormattedValue(string initial) {
   string formatRegex = @"^(?<First>[\d]{7})(?<Second>[\d]{4})(?<Third>[\d]{3})