如何将一个句子分成字母并在C#中存储为一个String数组?

时间:2014-02-16 20:28:03

标签: c# arrays string indexof

我在互联网上找到了这个:

char[] characters = "this is a test".ToCharArray();

但是这个商店是char数组。我希望能够将它存储到String数组中,因为我只使用String后才能使用它。

或者是否有另一种方法将所有字母放在一个数组中,然后选择一个数组的索引,其中的值与数组中的字母相同。

像这样:

String[] alphabet = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", " "};

现在char[]的第一个字母将是"t"

现在我需要的是索引:19存储在列表中。

1 个答案:

答案 0 :(得分:6)

string[] arr = "this is a test".Select(c => c.ToString()).ToArray();

存储您不需要此alphabet数组

的索引
int[] indexes = "this is a test".Select(c => (int)(c-'a')).ToArray();

您可以在LinqPad中看到输出

enter image description here

这是与您的问题最相似的方式,但我不认为使用IndexOf n次是一个很好的解决方案

List<char> alphabet = "abcdefghijklmnopqrstuvwxyz  ".ToList();
int[] arr = "this is a test".Select(c => alphabet.IndexOf(c)).ToArray();