vb.net 创建一个字符串并将文本附加到它

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5360303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 15:22:15  来源:igfitidea点击:

Create a string and append text to it

vb.net

提问by Voldemort

Funny, I had a textbox and I could append strings to it.

有趣的是,我有一个文本框,我可以向它附加字符串。

But now I create a string like this:

但现在我创建了一个这样的字符串:

    Dim str As String = New String("")

And I want to append to it other strings. But there is no function for doing so. What am I doing wrong?

我想向它附加其他字符串。但是没有这样做的功能。我究竟做错了什么?

回答by Philip Fourie

Concatenate with & operator

与 & 运算符连接

Dim str as String  'no need to create a string instance
str = "Hello " & "World"

You can concate with the + operator as well but you can get yourself into trouble when trying to concatenate numbers.

您也可以使用 + 运算符进行连接,但是在尝试连接数字时可能会遇到麻烦。


Concatenate with String.Concat()


String.Concat()连接

str = String.Concat("Hello ", "World")

Useful when concatenating array of strings

连接字符串数组时很有用


StringBuilder.Append()


StringBuilder.Append()

When concatenating large amounts of strings use StringBuilder, it will result in much better performance.

当使用StringBuilder连接大量字符串时,它会带来更好的性能。

    Dim sb as new System.Text.StringBuilder()
    str = sb.Append("Hello").Append(" ").Append("World").ToString()

Strings in .NET are immutable, resulting in a new String object being instantiated for every concatenation as well a garbage collection thereof.

.NET 中的字符串是不可变的,这导致为每个连接及其垃圾收集实例化一个新的 String 对象。

回答by TJTex

Another way to do this is to add the new characters to the string as follows:

另一种方法是将新字符添加到字符串中,如下所示:

Dim str As String

str = ""

To append text to your string this way:

要以这种方式将文本附加到您的字符串中:

str = str & "and this is more text"

回答by Kasper Holdum

Use the string concatenation operator:

使用字符串连接运算符:

Dim str As String = New String("") & "some other string"

Strings in .NET are immutable and thus there exist no concept of appending strings. All string modifications causes a new string to be created and returned.

.NET 中的字符串是不可变的,因此不存在附加字符串的概念。所有字符串修改都会导致创建并返回一个新字符串。

This obviously cause a terrible performance. In common everyday code this isn't an issue, but if you're doing intensive string operations in which time is of the essence then you will benefit from looking into the StringBuilder class. It allow you to queue appends. Once you're done appending you can ask it to actually perform all the queued operations.

这显然导致了糟糕的表现。在普通的日常代码中,这不是问题,但如果您正在执行密集的字符串操作,其中时间至关重要,那么您将从查看 StringBuilder 类中受益。它允许您排队追加。完成追加后,您可以要求它实际执行所有排队操作。

See "How to: Concatenate Multiple Strings"for more information on both methods.

有关这两种方法的更多信息,请参阅“如何:连接多个字符串”