字符反向排列
比如输一个句子:your idea is too abstract to understand.把它变成understand to abstract too is idea your.
这是一个软件公司笔试题目
------解决方案--------------------用StringBuffer缓冲区处理就可以了.
先把字符存在StringBuffer strb中,然后用charAt从后想前驱除,for(int i=strb;i> =0;i++)
可以解决倒序取出.
------解决方案--------------------String[] strings = sourceString.split( ' ');
StringBuffer buffer = new StringBuffer();
for(int i=strings.length-1; i> =0; i--) {
buffer.append(strings[i]);
if(i> 0) {
buffer.append( ' ');
}
}
String result = buffer.toString();
还可以用StringTokenizer,不过很久没用了,忘记怎么用了……
------解决方案--------------------public class remove
{
public static void main(String[] args)
{
String str= "your idea is too abstract to understand ";
StringBuffer strb=new StringBuffer(str.length());
for(int i=str.length()-1;i> =0;i--)
{
strb.append(str.charAt(i));
}
System.out.println(strb.toString());
}
}
------解决方案--------------------帮你写了个完整的程序,算法不是非常好,但是可以实现你需要的功能,主要思想就是分离出每个单词:
import java.io.*;
public class StringTest
{
public static void main(String[] args)throws
IOException {
StringBuffer buf1, buf2;
buf2 = new StringBuffer();
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
System.out.print( "Input String: ");
buf1 = new StringBuffer(read.readLine());
int i, j = buf1.length();
for(i = buf1.length() - 1; i > = 0; i--)
{
if(buf1.charAt(i) == ' ')
{
buf2.append(buf1.substring(i + 1, j) + " ");
j = i;
}
else if(i == 0)
{
buf2.append(buf1.substring(i , j));
}
}
System.out.println( "Output String: " + buf2);
}
}
------解决方案--------------------/* 程序:字符反向排列 TestStr */
import java.io.BufferedReader;
import
java.io.IOException;
import java.io.InputStreamReader;
public class TestStr{
public static void getString()throws IOException{ //定义函数
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));//读取
for(;;){ //一直循环下去
System.out.print( "Hello,Please Enter: "); //打印提示输入
String line=in.readLine(); //读取一行
if(line==null || line.equals( "quit ")){ //如读到EOF或quit
break; //循环中断
}
StringBuffer str=new StringBuffer(line); //使用一个StringBuffer
for(int i=str.length()-1;i> =0;i--){ //对于每个字符从最后一个
System.out.print(str.charAt(i)); //执行倒转操作
}
System.out.print( " ");
System.out.println();
}
}
public static void main(String[] args) throws IOException{
getString(); //调用函数
}
}