将字符串转换为包含其字母的数组
本文关键字:数组 包含其 字符串 转换 | 更新日期: 2023-09-27 18:14:36
我要做的就是取一个字符串
string test = "hello";
,然后将其转换为数组:
string[] testing = { "h", "he", "hel", "hell", "hello" };
这可能吗?
尝试使用Linq:
string test = "hello";
string[] testing = Enumerable
.Range(1, test.Length)
.Select(length => test.Substring(0, length))
.ToArray();
测试: // h, he, hel, hell, hello
Console.Write(string.Join(", ", testing));
你也可以这样做:
List<string> list = new List<string>();
for(int i = 1; i <= hello.Length; i++) {
list.Add(hello.Substring(0,i));
}
Console.WriteLine(string.Join(", ", list.ToArray()));
我推荐Dmitry的LINQ版本,但是如果你想要一个简单的版本,使用像你原来的问题一样的数组:
string input = "hello";
string[] output = new string[input.Length];
for( int i = 0; i < test.Length; ++i )
{
output[i] = test.Substring( 0, i + 1 );
}
string test = "hello";
string[] arr = new string[] {test.Substring(0,1), test.Substring(0,2), test.Substring(0,3), test.Substring(0,4), test.Substring(0,5)};
是的,你使用Linq。
string test = "hello";
List<string> lst = new List<string>();
int charCount = 1;
while (charCount <= test.Length)
{
lst.Add(string.Join("", test.Take(charCount).ToArray()));
charCount++;
}
string[] testing = lst.ToArray();