zoukankan      html  css  js  c++  java
  • 字符串中的单词反转

    题目

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

    例如: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);
        }
    }
    
    
  • 相关阅读:
    SQL SERVER 2008的数据压缩
    protected,internal和protected internal
    CSS笔记
    太吓人了!妈妈必看:国内人贩子抢孩子竟使出狠招
    ASP.NET上传图片的简单方法
    VS2005快捷键大全
    判断ExecuteScalar()是否返回结果
    AppSettings和ConnectionStrings的区别
    VSS中的签入和签出
    对目前工作烦躁的人来看看,你真正明白多少
  • 原文地址:https://www.cnblogs.com/SunAlbert/p/13682079.html
Copyright © 2011-2022 走看看