Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing the order of a string value

I have the following function which reverses a string value's display order. I'm new to Swift and I'm trying to understand it's logic. What is going on with the '!pleh' value that it turns into 'Help!' ? Thanks

func reverse(_ s: String) -> String {
 var str = ""
 for character in s.characters {
    str = "\(character)" + str
 }
 return str
}
print (reverse("!pleH"))
like image 413
Yiu Chung Wong Avatar asked Jan 21 '17 16:01

Yiu Chung Wong


People also ask

Which function returns the reverse order of a string value?

The REVERSE function accepts a character expression as its argument, and returns a string of the same length, but with the ordinal positions of every logical character reversed.

How do you reverse the order of a string in Java?

To reverse a string in java, we can first convert it to StringBuilder which is nothing but a mutable string. Class StringBuilder provides an inbuilt function called reverse(), which reverses the given string and provides you with the final output.

What returns the characters in the string in reverse order?

With a string as an argument, reversed() returns an iterator that yields characters from the input string in reverse order.


1 Answers

In swift 4.0, directly call reversed on a string will get the job done

let str = "abc"
String(str.reversed()) // This will give you cba
like image 87
Fangming Avatar answered Oct 03 '22 11:10

Fangming