【问题标题】:how to split a sentence into letters and store as a String array in C#?如何在 C# 中将句子拆分为字母并存储为字符串数组?
【发布时间】:2014-02-16 20:28:02
【问题描述】:

我在网上找到了这个:

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。

【问题讨论】:

    标签: c# arrays string indexof


    【解决方案1】:
    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 中看到输出

    就是这样,和你的问题最相似,但我不认为使用IndexOf n 次是一个好的解决方案

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

    【讨论】:

    • 非常感谢!立即修复了我需要的东西:)。不知道这个问题是否有点愚蠢,但我 2 天前才开始使用 c#。再次感谢。
    • @L.B 是我们同时更新的那些时间之一......我会再次添加它。
    猜你喜欢
    • 1970-01-01
    • 2021-11-15
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多