在字符串中设置字符 [英] set character in string

查看:106
本文介绍了在字符串中设置字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在字符串中设置 - 我该怎么办?



例如,02700060024112是字符串

然后我存储在数据库字符串为0270006-0024-112



我该怎么办???

解决方案

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


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



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



最后,您仍然可以通过调用实例方法 StringBuilder.ToString()(重写<$)来返回字符串C $ C> 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} )(小于?第三> [\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})


这篇关于在字符串中设置字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆