如何获取字符串中的特定字符?

问题描述 投票:0回答:1

我有一个问题,我需要循环字符串并单独打印每个字符:

var abc = MyFunction('abc')
abc() // should return 'a' on this first call
abc() // should return 'b' on this second call
abc() // should return 'c' on this third call
abc() // should return 'a' again on this fourth call
c# asp.net .net function methods
1个回答
1
投票

基本循环

据您的问题所述(根据我的理解),您希望重复调用一个方法并让该方法返回与当前调用相对应的字符串的索引。我会研究 for 循环string.Substring(int),您也可以将字符串作为 char 数组访问(我在下面这样做)。

static void Main() {
    string myString = "SomeStringData";
    for (int i = 0; i < myString.Length; i++)
        Console.Write(GetCharacter(myString, i));
}
static char GetCharacter(string data, int index) => data[index];

可以修改上面的代码以进行顺序调用,直到需要停止循环为止,这将满足到达字符串末尾后返回第一个索引的条件:

string myString = "abc";
for (int i = 0; i < myString.Length; i++) {
    Console.Write(GetCharacter(myString, i);

    // This will reset the loop to make sequential calls.
    if (i == myString.Length)
        i = 0;
}

如果您希望逃脱上面的循环,则需要添加一些条件逻辑来确定循环是否应中断,或者不进行循环,只需单独调用提供的

GetCharacter(string, int)
方法即可。另外,如果确实需要,您应该只修改迭代变量
i
;在这种情况下,你可以切换到 while 循环,这会更合适:

string myString = "abc";
string response = string.Empty;
int index = 0;
while (response.TrimEnd().ToUpper() != "END") {
    Console.WriteLine(GetCharacter(myString, index++));
    Console.WriteLine("If you wish to end the test please enter 'END'.");
    response = Console.ReadLine();

    if (index > myString.Length)
        index = 0;
}

获取角色(表情体与全身)

C# 6 引入了将方法编写为表达式的能力;写成表达式的方法称为 Expression-Bodied-Member。例如,以下两种方法的功能完全相同:

static char GetCharacter(string data, int index) => data[index];
static char GetCharacter(string data, int index) {
    return data[index];
}

表达式主体定义使您能够以非常简洁、可读的形式提供成员的实现。只要任何受支持的成员(例如方法或属性)的逻辑由单个表达式组成,您就可以使用表达式主体定义。

© www.soinside.com 2019 - 2024. All rights reserved.