I'm doing practice for C#, and the problem requires me to make a program that reverses words. I have the answer, but in my search for a solution, I got a weird output that doesn't make sense.
This is the code that leads to the weird output:
using System;
namespace stars
{
public class Reverse
{
public void SpinWords(string sentence)
{
int end_index = sentence.Length - 1;
string rev_sentence = "";
for (int i = end_index; i >= 0; i--)
{
string letter = sentence.Substring(i, 1);
rev_sentence = string.Concat(rev_sentence, i);
Console.Write(rev_sentence);
}
}
}
}
which has a large random numerical output, whereas I would have expected actual letters to come up.
and incase you were wondering this was my solution for a correct output:
using System;
namespace stars
{
public class Reverse
{
public void SpinWords(string sentence)
{
//Obtain the largest index in sentence
int end_index = sentence.Length - 1;
//Place letters backwards one-by-one to reverse string
for (int i = end_index; i >= 0; i--)
{
string letter = sentence.Substring(i, 1);
Console.Write(letter);
}
}
}
}