0
Q:

how to reverse a string

'String'[::-1] #-> 'gnirtS'
7
'hello world'[::-1]
'dlrow olleh'
In this particular example, the slice statement [::-1] means 
start at the end of the string and end at position 0, 
move with the step -1, negative one, which means one 
step backwards.
#From w3schools.com
14
'hello world'[::-1]
'dlrow olleh'
20
String str = "Hello";
String reverse(String str){
  StringBuilder sb = new StringBuilder();
  sb.append(str);
  sb.reverse();
  return sb.toString();
}
9
#linear

def reverse(s): 
  str = "" 
  for i in s: 
    str = i + str
  return str

#splicing
'hello world'[::-1]

#reversed & join
def reverse(string): 
    string = "".join(reversed(string)) 
    return string
  
 
  
9
#include <stdio.h>
#include <string.h>
int main()
{
   char s[100];

   printf("Enter a string to reverse\n");
   gets(s);

   strrev(s);

   printf("Reverse of the string: %s\n", s);

   return 0;
}
3
var="12345"
copy=${var}

len=${#copy}
for((i=$len-1;i>=0;i--)); do rev="$rev${copy:$i:1}"; done

echo "var: $var, rev: $rev"
0
1. Create a temporary byte[]  of length equal 
   to the length of the input string.
2. Store the bytes (which we get by using 
   getBytes() method) in reverse order into 
   the temporary byte[] .
3. Create a new String abject using byte[] to
   store result.
0
//make a scanner object
Scanner input = new Scanner(System.in);

//take in an input string and store it inside a <String> variable
System.out.println("Enter the string: ");
String string = input.nextLine();

//convert string to character arraylist by first creating
//an array list for the characters in correct order
//and an array list for what we will use
//to store the characters in reverse order later in the code
ArrayList<Character> chars = new ArrayList<Character>();
ArrayList<Character> reversed = new ArrayList<Character>();

//put all the characters from string into chars arrayList
for (char c : string.toCharArray()) {
    chars.add(c);
}

//get the size of the arraylist
Integer length = chars.size() - 1;
Integer x = 0;

//loop all the elements in the array chars into reversed arraylist in reverse order
while(x < chars.size()) {
    reversed.add(chars.get(length));
    length -= 1;
    x += 1;
}
-1
text = 'this is a string'
txt = "Hello World"[::-1]
  
 #or 
reversedstring = text[::-1]
print(reversedstring)
print(txt) 
-1

New to Communities?

Join the community