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

C# 如何获取字符串中的特定字符?,c#,asp.net,.net,function,methods,C#,Asp.net,.net,Function,Methods,我遇到了一个问题,需要在字符串上循环并单独打印每个字符: 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

我遇到了一个问题,需要在字符串上循环并单独打印每个字符:

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

你真的应该澄清你的问题;请随意阅读

基本循环

就您的问题而言(据我所知),您希望重复调用一个方法,并让该方法返回与当前调用对应的字符串的索引。我将查看和,您也可以将字符串作为char数组访问(我在下面这样做)

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

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

static char GetCharacter(string data, int index) => data[index];
static char GetCharacter(string data, int index) {
    return data[index];
}
表达式体定义允许您以非常简洁、可读的形式提供成员的实现。只要任何受支持成员(如方法或属性)的逻辑由单个表达式组成,就可以使用表达式体定义


你忘了描述问题和提出问题的那一部分…那是什么意思?我的问题不可理解?这意味着你没有问任何问题。你模糊地描述了什么似乎是家庭作业,标记了一些技术,仅此而已。您编写了哪些代码,哪些代码没有按预期工作?实际问题是您没有努力解决此问题,因此无论答案多么简单,这都是“请为我编写代码”。没问题,Khayam。请检查一下,也许可以坐飞机。您可以根据需要多次编辑问题以添加其他信息。可能您可以进行的最有价值的编辑是添加您尝试过的代码并指出问题所在。如果这解决了您的问题,请确保将您的问题标记为已回答。static char GetCharacter(string data,int index)=>data[index];函数声明在这个函数C#7语法中实际要做什么允许您将单行方法(函数)编写为表达式。上述返回如:
返回数据[索引]。我会更新帖子来澄清这一点。
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;
}
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;
}
static char GetCharacter(string data, int index) => data[index];
static char GetCharacter(string data, int index) {
    return data[index];
}