I'm studing C# for two weeks. And I have problem, I don't know how 4th line of this code works, namely new string(charArray)
string s = "Hello";
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
Console.WriteLine(new string(charArray));
Thank you all for responding!
CodePudding user response:
string s = "Hello";
This creates a new string, “Hello” assigned to a variable s
char[] charArray = s.ToCharArray();
This takes each character in the string s
and puts it into an array: [ 'H', 'e', 'l', 'l', 'o' ]
Array.Reverse(charArray);
This takes the array and reverses the contents: [ 'o', 'l', 'l', 'e', 'H' ]
. This does the operation in memory to the array itself so you don’t need to reassign it.
Console.WriteLine(new string(charArray));
This is doing two things: Assigning a new string that will contain each character in the array and then that value is being passed into Console.WriteLine which will write to the console output stream:
olleH
You could break that up into two statements for clarity:
string s = new string(charArray);
Console.WriteLine(s);
CodePudding user response:
The new
keyword means we are calling a constructor for the string
type, specifically one that expects a char[]
as an argument.