C# 不使用 Split 函数将字符串转换为数组

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

Convert string to array in without using Split function

c#arraysstring

提问by peanut

Is there any way to convert a string ("abcdef") to an array of string containing its character (["a","b","c","d","e","f"]) without using the String.Splitfunction?

有没有办法在不使用函数的情况下将字符串 ( "abcdef")转换为包含其字符 ( ["a","b","c","d","e","f"])的字符串数组String.Split

采纳答案by jason

So you want an array of string, one chareach:

所以你想要一个数组stringchar每个:

string s = "abcdef";
string[] a = s.Select(c => c.ToString()).ToArray();

This works because stringimplements IEnumerable<char>. So Select(c => c.ToString())projects each charin the stringto a stringrepresenting that charand ToArrayenumerates the projection and converts the result to an array of string.

这是有效的,因为string实现了IEnumerable<char>. 因此,将中的Select(c => c.ToString())每个投影到一个表示该并枚举投影并将结果转换为.charstringstringcharToArraystring

If you're using an older version of C#:

如果您使用的是旧版本的 C#:

string s = "abcdef";
string[] a = new string[s.Length];
for(int i = 0; i < s.Length; i++) {
    a[i] = s[i].ToString();
}

回答by G-Wiz

Yes.

是的。

"abcdef".ToCharArray();

回答by Adam Gritt

You could use linq and do:

您可以使用 linq 并执行以下操作:

string value = "abcdef";
string[] letters = value.Select(c => c.ToString()).ToArray();

This would get you an array of strings instead of an array of chars.

这会给你一个字符串数组而不是一个字符数组。

回答by War

Bit more bulk than those above but i don't see any simple one liner for this.

比上面的要大一些,但我没有看到任何简单的单衬。

List<string> results = new List<string>; 

foreach(Char c in "abcdef".ToCharArray())
{
   results.add(c.ToString());
}


results.ToArray();  <-- done

What's wrong with string.split???

string.split 有什么问题???

回答by efren

Why don't you just

你为什么不只是

string value="abcd";

value.ToCharArray();

textbox1.Text=Convert.toString(value[0]);

to show the first letter of the string; that would be 'a' in this case.

显示字符串的第一个字母;在这种情况下,这将是“a”。