Печать обратной строки без использования какой-либо предопределенной функции? - PullRequest
6 голосов
/ 10 апреля 2010

Как напечатать обратную строку java is object orientated language без использования какой-либо предопределенной функции, например reverse()?

Ответы [ 34 ]

0 голосов
/ 10 декабря 2015

Так же можно сделать и

char c[]=str.toCharArray();
  int i=c.lenght-1;
public void printReverseString(char[] c, int i){
       if(i==-1) return;
       System.out.println(c[i]);
       printReverseString(c,--i);
   }   
0 голосов
/ 23 июня 2015

Очень просто использовать цикл while

public class Test {
public static void main(String[] args) {
    String name = "subha chandra";
    int len = name.length();
    while(len > 0){
        len--;
        char c = name.charAt(len);
        System.out.print(c); // use String.valueOf(c) to convert char to String
    }
}    
}
0 голосов
/ 27 апреля 2015
package com.ofs;

public class ReverseWordsInString{
public static void main(String[] args) {

    String str = "welcome to the new world and how are you feeling ?";

    // Get the Java runtime
    Runtime runtime = Runtime.getRuntime();
    // Run the garbage collector
    runtime.gc();
    // Calculate the used memory
    long firstUsageMemory = runtime.totalMemory() - runtime.freeMemory();
    System.out.println("Used memory in bytes: " + firstUsageMemory);
    System.out.println(str);
    str = new StringBuffer(str).reverse().toString();
    int count = 0;
    int preValue = 0;
    int lastspaceIndexVal = str.lastIndexOf(" ");
    int strLen = str.length();
    for (int i = 0; i < strLen - 1; i++) {
        if (Character.isWhitespace(str.charAt(i))) {
            if (i - preValue == 1 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 2 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 3 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 4 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 5 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.substring(i - 2, i - 1) + str.charAt(i - 3)
                        + str.charAt(i - 3) + str.charAt(i - 5)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 6 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.charAt(i - 6) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 7 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.charAt(i - 6) + str.charAt(i - 7)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 8 && count == 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.charAt(i - 6) + str.charAt(i - 7)
                        + str.charAt(i - 8) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 2 && count != 0) {
                str = str.substring(0, preValue) + str.charAt(i - 1)
                        + str.substring(i, strLen);
                preValue = i;
            } else if (i - preValue == 3 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.substring(i, strLen);
                preValue = i;
            } else if (i - preValue == 4 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.substring(i, strLen);
                preValue = i;
            } else if (i - preValue == 5 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 6 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 7 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.charAt(i - 6) + str.substring(i, strLen);
                preValue = i;
                count++;
            } else if (i - preValue == 8 && count != 0) {
                str = str.substring(0, preValue + 1) + str.charAt(i - 1)
                        + str.charAt(i - 2) + str.charAt(i - 3)
                        + str.charAt(i - 4) + str.charAt(i - 5)
                        + str.charAt(i - 6) + str.charAt(i - 7)
                        + str.substring(i, strLen);
                preValue = i;
                count++;
            }
            if (lastspaceIndexVal == preValue) {
                if (strLen - lastspaceIndexVal == 2 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1);
                    preValue = i;
                } else if (strLen - lastspaceIndexVal == 3 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2);
                    preValue = i;
                } else if (strLen - lastspaceIndexVal == 4 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2)
                            + str.charAt(strLen - 3);
                    preValue = i;
                    count++;
                } else if (strLen - lastspaceIndexVal == 5 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2)
                            + str.charAt(strLen - 3)
                            + str.charAt(strLen - 4);
                    preValue = i;
                } else if (strLen - lastspaceIndexVal == 6 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2)
                            + str.charAt(strLen - 3)
                            + str.charAt(strLen - 4)
                            + str.charAt(strLen - 5);
                    preValue = i;
                    count++;
                } else if (strLen - lastspaceIndexVal == 7 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2)
                            + str.charAt(strLen - 3)
                            + str.charAt(strLen - 4)
                            + str.charAt(strLen - 5)
                            + str.charAt(strLen - 6);
                    preValue = i;
                } else if (strLen - lastspaceIndexVal == 8 && count != 0) {
                    str = str.substring(0, preValue + 1)
                            + str.charAt(strLen - 1)
                            + str.charAt(strLen - 2)
                            + str.charAt(strLen - 3)
                            + str.charAt(strLen - 4)
                            + str.charAt(strLen - 5)
                            + str.charAt(strLen - 6)
                            + str.charAt(strLen - 7);
                    preValue = i;
                }
            }
        }
    }
    runtime.gc();
    // Calculate the used memory
    long SecondaryUsageMemory = runtime.totalMemory()
            - runtime.freeMemory();
    System.out.println("Used memory in bytes: " + SecondaryUsageMemory);
    System.out.println(str);
}
}
0 голосов
/ 16 января 2013
import java.util.*;
public class Restring {

public static void main(String[] args) {
  String input,output;
  Scanner kbd=new Scanner(System.in);
  System.out.println("Please Enter a String");
  input=kbd.nextLine();
  int n=input.length();

  char tmp[]=new char[n];
  char nxt[]=new char[n];

  tmp=input.toCharArray();
  int m=0;
  for(int i=n-1;i>=0;i--)
  {
      nxt[m]=tmp[i];
      m++;
  }

  System.out.print("Reversed String is   ");
  for(int i=0;i<n;i++)
  {
      System.out.print(nxt[i]);
  }

}
0 голосов
/ 31 января 2015
public class ReverseString {

public static void main(String[] args) {

    reverseString("HELLO");
}

public static String reverseString(String s){
    char []arr=s.toCharArray();
    for(int i= (arr.length)-1;i>=0;i--){
        System.out.print(arr[i]);
    }
    String str=String.copyValueOf(arr);
    return str;
}
0 голосов
/ 09 июля 2013
 public class ReverseWithoutStringAPI {

public static void main(String[] args) {

      String st="hello";

        StringBuffer b=new StringBuffer();

        for(int i=st.length()-1;i>=0;i--){

            b.append(st.charAt(i)); }

        System.out.println("reverse:::"+b);
}
}
0 голосов
/ 31 марта 2015
public class Match {
 void comp(String s1, String s2) {
    char[] charArray1 = s1.toCharArray();
    char[] charArray2 = s2.toCharArray();

    int length1 = charArray1.length;        

    int length2 = charArray2.length;       
    int flag = 0;

    if (length1 == length2) {
        for (int i = 0; i <= length1 - 1; i++) {
            if (charArray1[i] == charArray2[i]) {
                System.out.println("index are matched:" + " " + charArray1[i] + " " + "in index-" + i);

            } else {
                flag = 1;
                System.out.println("index are not matched:" + " " + charArray1[i] + " " + "in index-" + i);
                System.out.println("index are not matched:" + " " + charArray2[i] + " " + "in index-" + i);                    
            }
        }
    } else {
        System.out.println("Your string are not matched by length");
    }
    if (flag == 0) {
        System.out.println("Your string  matched with other String");
    } else {
        System.out.println("Your string are not matched");
    }
}
public static void main(String[] args) {
    java.util.Scanner sc = new java.util.Scanner(System.in);
    System.out.println("Enter the 1st String:");
    String s1 = sc.nextLine();
    System.out.println("Enter the 2nd string");
    String s2 = sc.nextLine();
    Match m = new Match();
    m.comp(s1, s2);
}
}
0 голосов
/ 02 ноября 2011

У меня было это некоторое время назад, и, ответив очевидным ответом StringBuffer.reverse (), они спросили: «Можете ли вы обратить массив символов без использования этих методов API и достичь результата без буферизации в новый массив символов? '

В то время, когда я осознал, что мне нужно было перебрать только половину длины массива char, я сделал немного хэш объяснения фактического кода, который нужно было в него ввести (это был словесный вопрос). Во всяком случае, я попробовал это, когда я вернулся домой и придумал это:

public class StringReverse {

public static void main(String[] args){

    String a = "String";

    char[] aChar = a.toCharArray();

    for (int i = (aChar.length-1)/2 ; i >= 0 ; i--){
        int posA = i;
        int posB = (aChar.length-1-i);
        char tmpA = aChar[posA];
        char tmpB = aChar[posB];
        System.out.println("Setting " + posA + " to " + tmpB);
        System.out.println("Setting " + posB + " to " + tmpA);

        aChar[posA] = tmpB;
        aChar[posB] = tmpA;
    }

    System.out.println(aChar);
}

}

Очевидно, что этого можно добиться с помощью меньшего количества кода, но я думаю, что временные присваивания в методе проясняют, что делает код.

Выводит что-то вроде:

Setting 2 to i
Setting 3 to r
Setting 1 to n
Setting 4 to t
Setting 0 to g
Setting 5 to S

gnirtS

Я бы сказал, что это скорее вопрос интервью, чем домашнее задание.

0 голосов
/ 15 мая 2015

ReverseString.java

public class ReverseString {
    public static void main(String[] args) {
        String str = "Ranga Reddy";
        String revStr = reverseStr(str);
        System.out.println(revStr);     
    }

    // Way1 - Recursive
    public static String reverseStr(String str) {
        char arrStr[] = reverseString(0, str.toCharArray());
        return new String(arrStr);
    }

    private static char[] reverseString(int charIndex, char[] arr) {     
        if (charIndex > arr.length - (charIndex+1)) {
          return arr;
        }

        int startIndex = charIndex;
        int endIndex = arr.length - (charIndex+1);

        char temp = arr[startIndex];        
        arr[startIndex] = arr[endIndex];
        arr[endIndex] = temp;      
        charIndex++;       
        return reverseString(charIndex++, arr);
    }

    // Way2
    private static String strReverse(String str) {
        char ch[] = new char[str.length()];
        for (int i = str.length() - 1, j = 0; i >= 0; i--) {
            ch[j++] = str.charAt(i);
        }
        return new String(ch);
    }
}
0 голосов
/ 28 февраля 2013
public String reverse(String arg)
{
    String tmp = null;
    if (arg.length() == 1)
    {
        return arg;
    }

    else
    {

        String lastChar = arg.substring(arg.length()-1,arg.length());

        String remainingString = arg.substring(0, arg.length() -1);

        tmp = lastChar + reverse(remainingString);
        return tmp;


    }
}
...