不使用字符串函数反转字符串

时间:2013-12-05 06:48:34

标签: java

如何在不使用字符串函数的情况下编写java程序来反转字符串?

 String a="Siva";

 for(int i=0;i<=a.length()-1;i++)
 {
     System.out.print(a.charAt(i));
 }
     System.out.println("");

 for(int i = a.length() - 1; i >= 0; --i)
 {
     System.out.print(a.charAt(i)); 
 }

此处charAt()a.length()是字符串函数

4 个答案:

答案 0 :(得分:7)

这将有助于

public class StringReverse {

   public static void main(String[] args){
    String str = "Reverse";
    StringBuilder sb = new StringBuilder(str);
    str = sb.reverse().toString();
    System.out.println("ReverseString : "+str);
  }

}

没有使用String方法

答案 1 :(得分:3)

String s = "abcdef";
char c[] = s.toCharArray();

for( int i = c.length -1; i>=0; i--)
    System.out.print(c[i]);

答案 2 :(得分:3)

使用StringBuilder类或StringBuffer类已经有方法reverse()来反转字符串

StringBuilder str = new StringBuilder("india");
System.out.println("string = " + str);

// reverse characters of the StringBuilder and prints it
System.out.println("reverse = " + str.reverse());

// reverse is equivalent to the actual
str = new StringBuilder("malayalam");
System.out.println("string = " + str);

// reverse characters of the StringBuilder and prints it
System.out.println("reverse = " + str.reverse());

http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html

答案 3 :(得分:1)

下面是丑陋的黑客。它的概念,但它不会调用任何String方法。

import java.io.*;
import java.util.*;
public class Hello {
    public static String reverceWithoutStringMethods(String word){
        String result = "";
        //------ Write string to file -----------
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter( new FileWriter("tempfile"));
            writer.write(word);
        }
        catch ( IOException e) {}
        finally {
            try{
                if ( writer != null) writer.close( );
            }
            catch ( IOException e){}
        }
        //------ read string from file -------------
        RandomAccessFile f=null;
        try {
             f = new RandomAccessFile("tempfile", "r"); // Open file
            int length = (int) f.length(); // Get length
            // Read file
            byte[] data = new byte[length];
            f.readFully(data);
            // Reverse data
            for (int i=data.length; i>=0; i--){
                result += (char)data[i-1];
            }
        } catch(Exception e){}
        finally {
            try{
                f.close();
            }
            catch (Exception e){}
        }
        return result;
    }
    public static void main(String[] args) { 
        System.out.println(reverceWithoutStringMethods("Test"));
        System.out.println(reverceWithoutStringMethods(""));
    } 
}

输出:

tseT