简体   繁体   English

如何在vb.net中拆分?

[英]How to split in vb.net?

Is there any way to split and then join a string in a textbox? 有没有办法在文本框中拆分然后加入字符串?

Example: 例:

I had a textbox named Textbox1 that has a value of "001-2012-0116" then I want to split it by this ("-") and then join the resulting 3 strings 我有一个名为Textbox1的文本框,其值为"001-2012-0116"然后我想将其拆分(“ - ”),然后加入生成的3个字符串

Then the result will become "00120120116" 然后结果将变成"00120120116"

then I want to get the result and put it in a resultNumber whose datatype is string. 然后我想得到结果并将其放在resultNumber其数据类型为字符串。

To summarize it : 总结一下:

Textbox1(Value) = "001-2012-0116"

Dim resultNumber as String

resultNumber(Value) = "00120120116"

As others suggest, split isn't the best way to go in this case. 正如其他人所说,拆分不是这种情况下最好的方法。 You'll need to use String.Join() after splitting to get that expected result : 分割后你需要使用String.Join()来获得预期的结果:

Dim resultNumber = String.Join("", "001-2012-0116".Split("-"))

So it is kind of double work. 所以这是一种双重工作。 Will be more concise to simply replace dash ( - ) with empty string : 简单地用空字符串替换短划线( - )会更简洁:

Dim resultNumber = "001-2012-0116".Replace("-", "");

You want to use String.Replace() in this situation: 您希望在这种情况下使用String.Replace()

resultNumber = Textbox1.Value.ToString().Replace("-", String.Empty)

Obviously this keeps everything as a String , but if you want to use the string as numeric (as they are numeric) then you would need to convert it to an Integer . 显然,这会将所有内容保存为String ,但如果要将字符串用作数字(因为它们是数字),则需要将其转换为Integer

If you want to split the value into an array of strings then you can use the following, but you're not really wanting this result, but you asked about splitting strings... 如果你想将值拆分成一个字符串数组,那么你可以使用以下内容,但你并不是真的想要这个结果,但是你问到了拆分字符串......

Dim result As String() = words.Split("-")

You can try this approach as inspiration: 您可以尝试这种方法作为灵感:

Sub Main
Dim txt as String
Dim intVal as Int64
txt =  "001-2012-0116"

If(Int64.TryParse(txt.Replace("-",""), intVal))
Console.WriteLine(intVal)
End If

End Sub

I know this has been answered, but sometimes I prefer to use the RegularExpression Class. 我知道这已经得到了解答,但有时我更喜欢使用RegularExpression类。

In your case this is how it can be accomplished... 在你的情况下,这是如何实现的......

 Imports System.Text.RegularExpressions 'Need to import the namespace

 Dim resultNumber As String =  Regex.Replace(TextBox1.Text, "-", String.Empty) 'Do a simple replace on "-" 

On the other hand your doing a simple replace on a single string, so the answer that you accepted would be more suitable in this case. 另一方面,您在单个字符串上进行简单替换,因此您接受的答案在这种情况下更合适。 Regular expressions in my opinion are great when dealing with patterns and such. 在处理模式等时,我认为正则表达式很棒。

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

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