How to reverse a string

前端 未结 6 1255
北荒
北荒 2021-01-15 19:53

I need to reverse the string of a user\'s input.

I need it done in the simplest of ways. I was trying to do reverseOrder(UserInput) but it wasn\'t working.

相关标签:
6条回答
  • 2021-01-15 20:17

    There is an interesting method to do it so too.

       String input = "abc";
       //Here, input is String to reverse
       int b = input.length();
       String reverse = ""; // Declaring reverse String variable
         while(b!=0){
            //Loop for switching between the characters of the String input
            reverse += (input.charAt(b-1));
            b--;
            }
            System.out.println(reverse);
    
    0 讨论(0)
  • 2021-01-15 20:21

    I prefer using Apache's commons-lang for this kind of thing. There are all kinds of goodies, including:

    StringUtils.reverse("Hello World!");
    

    yields: !dlroW olleH

    StringUtils.reverseDelimited("Hello World!", ' ');
    

    yields: World! Hello

    0 讨论(0)
  • 2021-01-15 20:22

    If you are new to programming, which I guess you are, my suggestion is "Why use simple stuff?". Understand the internals and play some!!

    public static void main(String[] args) {
    String str = "abcasz";
    char[] orgArr = str.toCharArray();
    char[] revArr = new char[orgArr.length];
    for (int i = 0; i < orgArr.length;i++)  {
    revArr[i] = orgArr[orgArr.length - 1 - i];
    }
    String revStr = new String(revArr);
    System.out.println(revStr);
    
    0 讨论(0)
  • 2021-01-15 20:22

    Without going through the char sequence, easiest way:

    public String reverse(String post) {       
        String backward = "";
        for(int i = post.length() - 1; i >= 0; i--) {
            backward = backward + post.substring(i, i + 1);
        }        
        return backward;
    } 
    
    0 讨论(0)
  • 2021-01-15 20:31
    new StringBuilder(str).reverse().toString()
    

    java.util.Collections.reverseOrder is for sorting in reverse of normal order.

    0 讨论(0)
  • 2021-01-15 20:31
        public String reverseString(final String input_String)
              {
                  char temp;
                  char[] chars = input_String.toCharArray();
                  int N = chars.length;
                  for (int i = 0 ; i < (N / 2) ; i++)
                  {
                      temp = chars[i];
                      chars[i] = chars[N - 1 - i];
                      chars[N - 1 - i] = temp;
                  }
    
                  return new String(chars);
              }
    

    Run :

        Pandora
        arodnaP
    
    0 讨论(0)
提交回复
热议问题