编程语言
首页 > 编程语言> > Java反转字母文本

Java反转字母文本

作者:互联网

给定一个英语文本 ,将英语文本反转
例:When you were born,you were crying and everyone around you was smiling.Live your life so that when you die,you're the one who is smilling and everyone around you is crying.
输出:.crying is you around everyone and smilling is who one the re'you,die you when that so life your Live.smiling was you around everyone and crying were you,born were you When



public static void main(String[] args) {
  String s ="When you were born,you were crying and everyone around you was smiling.Live your life so that when you die,you're the one who is smilling and everyone around you is crying.";
          StringBuffer stringBuffer = new StringBuffer();
          stringBuffer.append(s);
          //在符号两端加空格
          for (int i = 0; i < stringBuffer.length(); i++) {
              if (!Character.isLetterOrDigit(stringBuffer.charAt(i)) && stringBuffer.charAt(i)!=' ') {
                  stringBuffer.insert(i," ");
                  stringBuffer.insert(i+2," ");
                  i+=2;
              }
          }
          String s1 = stringBuffer.toString();
          StringBuffer stringBuffer1 = new StringBuffer();

          //将空格变成数组
          String[] s2 = s1.split(" ");
          for (int i = s2.length - 1; i >=0 ; i--) {
              if (i!=0 && i != s2.length - 1){
                  stringBuffer1.append(s2[i]+" ");
              }else {
                  stringBuffer1.append(s2[i]);
              }
          }

          //将符号两端空格去除
          int length = stringBuffer1.length();
          for (int i = 0; i < length ; i++) {
              if (i!=0 && i!= stringBuffer1.length()-1 && !Character.isLetterOrDigit(stringBuffer1.charAt(i)) && stringBuffer1.charAt(i)!=' '){
                  stringBuffer1.deleteCharAt(i-1);
                  stringBuffer1.deleteCharAt(i);
                  length = length-2;
              }
          }
          System.out.println(stringBuffer1.toString());
      }
}

标签:everyone,Java,around,stringBuffer,字母,length,stringBuffer1,crying,文本
来源: https://www.cnblogs.com/chenglong0201/p/15549412.html