string 将字符串转换为字符数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9835959/
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 01:25:55  来源:igfitidea点击:

Converting a string to a char array

arraysvb.netstringchar

提问by Isuru

Let's say I have a string like this.

假设我有一个这样的字符串。

Dim str As String = "code"

I need to break this string down to an array of characters like this,

我需要将此字符串分解为这样的字符数组,

{"c", "o", "d", "e"}

How can I do this?

我怎样才能做到这一点?

回答by Tim Schmelter

Every string is an implicit char-array. So you can get the 3rd char by:

每个字符串都是一个隐式的字符数组。所以你可以通过以下方式获得第三个字符:

Dim char3 = str(2)

Edit: Just for the sake of completeness. You can also use String.ToCharArrayto convert the string instance to a new char-arrayinstance. The core benefit of using ToCharArrayis that the char-array you receive is mutable, meaning you can actually change each individual character.

编辑:只是为了完整性。您还可以使用String.ToCharArray将字符串实例转换为新char-array实例。使用的核心好处ToCharArray是您收到的字符数组是可变的,这意味着您实际上可以更改每个字符。

Note that you could also use LINQ. If you for example want the first three characters of a String:

请注意,您也可以使用LINQ. 例如,如果您想要字符串的前三个字符:

Dim firstThree As Char() = str.Take(3).ToArray()

回答by cHao

dim chars as Char() = str.ToCharArray()

回答by whytheq

Referencing @AlexeiLevenkov,

参考@AlexeiLevenkov,

You can use String.ToCharArrayto convert it to array of characters, or use ToArrayif you like LINQ more:

Dim delimStr As String = " ,.:"
Dim delimiter As Char() = delimStr.ToCharArray()

"foo".ToArray()

您可以使用 String.ToCharArray将其转换为字符数组, 如果您更喜欢 LINQ ,则可以使用 ToArray

Dim delimStr As String = " ,.:"
Dim delimiter As Char() = delimStr.ToCharArray()

"foo".ToArray()

(I added the above alternative as the duplicate question will be soon closed; it is worth keeping the LINQalternative.)

(我添加了上述替代方案,因为重复的问题将很快关闭;保留LINQ替代方案是值得的。)

回答by Shawn

I did some benchmarking and ToCharArray is approximately 30 times faster than LINQ's ToArray.

我做了一些基准测试,ToCharArray 比 LINQ 的 ToArray 快大约 30 倍。

回答by Shree

Try:

尝试:

Dim str As String = "code"
' Use For Each loop on string.
For Each element As Char In str 
Console.WriteLine(element)