字符串中的单词反转

题目

反转字符串,定义单词只能是字母,所以反转字母,但是不改变原来的整个字符串的位置

例如:a hello1 abc good!

​ 由于 hell1 与 good!不是单词所以不反转

​ a与abc是单词,所以要反转

思路

  • 通过空格分割字符串,保存在一个字符串数组中
  • 判断当前字符串是否为一个单词
    • 采用正则表达式"[a-zA-Z]+"
      • 其中 []代表或的关系
      • a-z与A-Z代表字母
      • ”+“代表出现一次或者多次
    • 利用字符串的meches方法
  • 如果是单词
    • 进行反转
      • 注意要重置临时区域
    • 放入答案容器res中
    • 对res进行toString方法调用
  • 如果不是单词
    • 直接放入答案容器res中
  • 最终返回res或者输出res

代码实现JAVA

package com.wang.test;

public class Myon1 {
    public static void main(String[] args) {
        String str = "a hello1 abc good!";
        //字符串的反转,单词反转,不是单词就不反转
        String[] st = str.split(" ");//通过空格切割,并且保存进数组

        StringBuilder res = new StringBuilder();
        for(int i = 0 ;i < st.length;i++){
            if(isVil(st[i])){
                StringBuilder stb = new StringBuilder();
               String tep  = String.valueOf(stb.append(st[i]).reverse()) ;//反转了

//                char[] chars = st[i].toCharArray();
//                char[] teemp =new char[chars.length];
//
//                for(int j = chars.length-1; j>=0;j--){
//                    teemp[chars.length-1-j] = chars[j];
//
//                }
//                String tep = new String(teemp);


                res.append(tep+" ");

            }else {
                res.append(st[i]+" ");
            }
        }
        System.out.println(res.toString());
    }

    public static boolean isVil(String s){
String st = "[a-zA-Z]+";
        return s.matches(st);
    }
}

原文地址:https://www.cnblogs.com/SunAlbert/p/13682079.html