I want to replace a string (that the user inputs) with the next character in the alphabet. I'm having trouble returning the next value from my loop. Error message: Index was outside the bounds of the array. I understand that the array ends, and that might be a problem from the 1 I entered. How would I go about solving this?
string inputString = "abcdefghijklmnopqqrstuvxyz";
char[] inputCharArray = inputString.ToCharArray();
char[] alphabetArray = "abcdefghijklmnopqrstuvxyz".ToArray();
var resultStr = "";
for (int i = 0; i < inputCharArray.Length; i )
{
if(alphabetArray.Contains(inputCharArray[i]))
resultStr = inputCharArray[i 1];
else
resultStr = inputCharArray[i];
}
System.Console.WriteLine(resultStr);
CodePudding user response:
You're getting an Out Of Range exception because i
will eventually equal the last index of your input array, and adding 1 to that number is beyond what the array has.
First, make it easier on yourself by making a function to convert a single char into the next letter.
Note, this answer assumes that you want to "wrap around" - the next letter after "z" goes back to "a".
char NextLetter(char input)
{
if (input < 'a' || input > 'z') // simple validation
throw new ArgumentException();
input = (char)1; // go to the next char value
if (input > 'z') // did you go past z?
input = 'a'; // go back to a
return input;
}
Yes, you can also do modulo, this method is the simple version.
Now you can loop through all the letters in your input to construct the output string. In addition, you don't need to .ToCharArray()
a string - a string already implements IEnumerable<char>
.
var input = "abcxyz";
var outputBuilder = new StringBuilder();
foreach (char letter in input)
{
outputBuilder.Append(NextLetter(letter));
}
Console.WriteLine(outputBuilder.ToString());
// prints "bcdyza"
CodePudding user response:
You can use Array.IndexOf
to find the index of the current character in the alphabet, then you can use the modulo operator (%
) to get the index of the next character in the alphabet (assuming the alphabet wraps from z
to a
in your desired solution):
string inputString = "abcdefghijklmnopqqrstuvxyz";
char[] inputCharArray = inputString.ToCharArray();
char[] alphabetArray = "abcdefghijklmnopqrstuvxyz".ToArray();
var resultStr = "";
for (var i = 0; i < inputCharArray.Length; i )
{
var indexInAlphabet = Array.IndexOf(alphabetArray, inputCharArray[i]);
var indexOfNextLetter = (indexInAlphabet 1) % alphabetArray.Length;
resultStr = alphabetArray[indexOfNextLetter];
}
Console.WriteLine(resultStr);