I have an issue where I need to loop over a string and print each character individually:
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
Basic Loop
As far as your question states (from my understanding), you would like to repeatedly call a method and have that method return the index of a string that corresponds to the current call. I would look into the for loop and string.Substring(int), you could also just access the string as a char array (which I do below).
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];
The code above can be modified to make sequential calls until you need to stop looping which will meet your condition of the first index being returned once the end of the string has been reached:
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;
}
If you wish to escape the loop above, you'll need to add some conditional logic to determine if the loop should be broken, or instead of looping, just make individual calls to the GetCharacter(string, int)
method supplied. Also, you should only modify the iteration variable i
if you truly need to; in this case you could switch to a while loop which would be more appropriate:
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;
}
Get Character (Expression Body vs Full Body)
C# 6 introduced the ability to write methods as expressions; a method written as an expression is called an Expression-Bodied-Member. For example, the two methods below function in the exact same manner:
static char GetCharacter(string data, int index) => data[index];
static char GetCharacter(string data, int index) {
return data[index];
}
Expression body definitions let you provide a member's implementation in a very concise, readable form. You can use an expression body definition whenever the logic for any supported member, such as a method or property, consists of a single expression.