-3

To reverse a string we convert it into an array of characters, then we use a for loop to print the reversed string. But in the below program we are getting characters from the string without converting it into characters. I am really confused how it has happened. Variable str is string then why str[i] is returning a character?

public static void Main() {
  string str = "hello mr singh";
  string temp ="";

  for (int i = str.Length - 1; i >= 0; i--) {
    temp += str[i];
  }
  Console.WriteLine("Reverse string:" + temp);
  Console.ReadLine();
}
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
Chota Vlog
  • 23
  • 6
  • and what returns `this[int index]` property of string class? – Selvin Sep 05 '19 at 13:35
  • https://referencesource.microsoft.com/#mscorlib/system/string.cs line 717 and following. That's why it's a char :) – Fildor Sep 05 '19 at 13:36
  • @HimBromBeere I'm not sure this question is a duplicate of that you've linked. It's actually nothing to do with reversing strings – Caius Jard Sep 05 '19 at 13:38
  • 1
    @ChotaVlog *variable str is string then why str[i] is returning a character?* because string has an indexer property `this[int index]` that returns the character at the given index. If I want to know what the 4th character of "Hello World" is, it's perfectly valid C# to say `char c = "Hello World"[3];` - see https://learn.microsoft.com/en-us/dotnet/api/system.string.chars?view=netframework-4.8 – Caius Jard Sep 05 '19 at 13:40
  • Linq solution: `string reversed = string.Concat(str.Reverse());` – Dmitry Bychenko Sep 05 '19 at 13:44
  • 1
    Using `temp += nextCharacter` to build a string is horribly inefficient, since that will copy the string-so-far every time you add a new character. Using StringBuilder is one of several more efficient ways to gradually build a string. – M Kloster Sep 05 '19 at 14:02

2 Answers2

1

Try this:

string str = "hello mr singh";
char[] arr = str.ToCharArray();
Array.Reverse(arr);
_revArray = string(arr);
Micha
  • 906
  • 6
  • 9
1

str is a string and you can reach each caractere of it using str[i], so to reverse the string the for loop begins from the last caractere int i = str.Length - 1 and store the results in a new string temp.

for example if you want to reverse the string "hello", the string length is 5 so the lopp will start from 4 so we will have:

str[4] = 'o', str[3] = 'l', str[2] = 'l', str[1] = 'e', str[0] = 'h'

finally store the results in the variable temp:

temp = str[4] + str[3]  + str[2] + str[1] + str[0];

so the resulted string is the concatenation of the caracters.

If you want a more efficient way to reverse a string check the answers for this question: Best way to reverse a string

Hamza
  • 440
  • 7
  • 20