请读写一段代码,将下面的句子的语序颠倒:
“Long long ago,there lived a king ”
提示(即把上述句子变成“king a lived there,ago long Long”)
注意there紧跟(,号)没有空格而(,号)紧跟ago没有空格,其它单词间是空格隔开 。相信大家明白题意了
“Long long ago,there lived a king ”
提示(即把上述句子变成“king a lived there,ago long Long”)
注意there紧跟(,号)没有空格而(,号)紧跟ago没有空格,其它单词间是空格隔开 。相信大家明白题意了
http://topic.csdn.net/u/20120616/22/9cb21687-f9ed-404a-8622-f573e478e7e4.html得到了单词和标点符号,输出控制一下就可以了
String s = "Long long ago, there lived a king";
String[] sa = s.split("(?=,)|\\s+");
for (int i=sa.length-1; i>=0; i--) {
System.out.printf((i>0 && sa[i-1].contains(",") ? "%s" : "%s "), sa[i]);
}
String[] ss=str.split(",");
str=ss[0]+" , "+ss[1];//晕乎。再加一个空格
ss=str.split(" ");
for(int i=ss.length-1; i>=0; i--) System.out.print(ss[i] +" ");
for example
String s = "Long long ago,there lived a king";
String[] sa = s.split("\\s+");
for (int i=sa.length-1; i>=0; i--) {
if (sa[i].contains(",")) {
String[] ss = sa[i].split(",", -1);
for (int j=ss.length-1; j>0; j--) {
System.out.printf("%s,", ss[j]);
}
System.out.printf("%s ", ss[0]);
} else {
System.out.printf("%s ", sa[i]);
}
}
String[] sa = s.split("(?=,)|\\s+");
for (int i=sa.length-1; i>=0; i--) {
System.out.printf((i>0 && sa[i-1].contains(",") ? "%s" : "%s "), sa[i]);
}
public class Tes
{
public static void main(String[] args)
{
String str="Long long ago,there lived a king";
String []yuju=str.split(",");
//返序后
StringBuffer fx_str=new StringBuffer();
for (int i = yuju.length-1; i >=0 ; i--)
{
String []danci=yuju[i].split(" ");
for (int j = danci.length-1; j >=0 ; j--)
{
if(j!=0)
{
fx_str.append(danci[j]).append(" ");
}
else
{
fx_str.append(danci[j]);
}
}
if(i!=0)
fx_str.append(",");
}
System.out.println(fx_str);
}
}
{
public static void main(String[] args)
{
String str="Long long ago,there lived a king,there lived a king";
String []yuju=str.split(",");
//返序后
StringBuffer fx_str=new StringBuffer();
for (int i = yuju.length-1; i >=0 ; i--)
{
String []danci=yuju[i].split(" ");
for (int j = danci.length-1; j >=0 ; j--)
{
fx_str.append(" ").append(danci[j]);
}
if(i!=0)
fx_str.append(",");
}
System.out.println(fx_str.toString().trim());
}}
虽然这种写法很好 但是你看错了楼主的题 注意there紧跟(,号)没有空格
String[] sa = s.split("(?=,)|\\s+|(?<=,)");
for (int i=sa.length-1; i>=0; i--) {
System.out.printf((i>0 && sa[i-1].contains(",")||sa[i].contains(",") ? "%s" : "%s "), sa[i]);
}阿宝的方法很好。不过逗号位置不对。稍微改了下