您的位置:首页 > 编程语言 > Java开发

java字符串反转,逆序输出(句子反转,单词不反转)

2013-05-03 23:13 363 查看
如果输入:My name is Xiaogang

输出:Xiaogang is name My

代码具有去句子前后空格功能,并且有注释

class String2Test
{
public static void main( String[] args )
{
if(args.length<1)
{
System.out.println("Error! ---Need parameter");
System.exit(-1);
}

StringBuffer s1 = new StringBuffer();  /* obtain original string */
StringBuffer s2 = new StringBuffer();  /* save the reverse string */
StringBuffer buffer = new StringBuffer();  /* the buffer for saving word */
s1.append(args[0]);
byte symbol;                          /* record the status, reading char or space */
char[] chars = new char[s1.length()];  /* the array for saving string to process */

s1.getChars(0,s1.length(),chars,0);

if(chars[chars.length-1]==' ' ||  chars[chars.length-1]=='\t')
symbol=0;
else
symbol=1;

/** scan and reverse the string **/
for( int i=(chars.length-1); i>=0; i--)
{
if(chars[i]!=' ' && chars[i]!='\t' )
{
if( symbol==0 )
{
symbol=1;
buffer.delete(0,buffer.length());
}
buffer.append(chars[i]);
}

else if( symbol==1)
{
symbol=0;
System.out.println(buffer.reverse());
s2.append(buffer);
s2.append(chars[i]);
}
}

/** process the head of the string **/
if(symbol==1)
{
System.out.println(buffer.reverse());
s2.append(buffer);
}

System.out.println(s2);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐