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

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


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


斯蒂芬大帝
浏览 411回答 1
1回答

qq_笑_17

你真的应该澄清你遇到的问题;请随时阅读如何提问。基本循环就您的问题而言(根据我的理解),您希望重复调用一个方法并让该方法返回与当前调用对应的字符串的索引。我会查看for 循环和string.Substring(int),您也可以将字符串作为字符数组访问(我在下面这样做)。static void Main() {&nbsp; &nbsp; string myString = "SomeStringData";&nbsp; &nbsp; for (int i = 0; i < myString.Length; i++)&nbsp; &nbsp; &nbsp; &nbsp; 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++) {&nbsp; &nbsp; Console.Write(GetCharacter(myString, i);&nbsp; &nbsp; // This will reset the loop to make sequential calls.&nbsp; &nbsp; if (i == myString.Length)&nbsp; &nbsp; &nbsp; &nbsp; i = 0;}如果您想逃避上面的循环,您需要添加一些条件逻辑来确定循环是否应该被破坏,或者只对GetCharacter(string, int)提供的方法进行单独调用而不是循环。此外,i如果确实需要,您应该只修改迭代变量;在这种情况下,您可以切换到更合适的while 循环:string myString = "abc";string response = string.Empty;int index = 0;while (response.TrimEnd().ToUpper() != "END") {&nbsp; &nbsp; Console.WriteLine(GetCharacter(myString, index++));&nbsp; &nbsp; Console.WriteLine("If you wish to end the test please enter 'END'.");&nbsp; &nbsp; response = Console.ReadLine();&nbsp; &nbsp; if (index > myString.Length)&nbsp; &nbsp; &nbsp; &nbsp; index = 0;}获取角色(表情身体 vs 全身)C# 6 引入了将方法编写为表达式的能力;写成表达式的方法称为Expression-Bodied-Member。例如,以下两种方法的功能完全相同:static char GetCharacter(string data, int index) => data[index];static char GetCharacter(string data, int index) {&nbsp; &nbsp; return data[index];}表达式主体定义允许您以非常简洁、易读的形式提供成员的实现。只要任何受支持成员(例如方法或属性)的逻辑包含单个表达式,就可以使用表达式主体定义。
打开App,查看更多内容
随时随地看视频慕课网APP