输入一个英文句子,包含字母大小写、逗号、句号和空格。把英文句子中的单词的字母顺序倒置
如:hello,I am good.
olleh,I ma doog.
package com.soft.wk; import java.util.regex.Matcher; import java.util.regex.Pattern; public class LetterFlashBack { public static void main(String[] args) throws Exception { String str = "hello,I am good."; String trim = str.trim(); StringBuffer sb = new StringBuffer(); if(trim != null && !trim.isEmpty()){ boolean flag = isEnglishNumber(trim); if(flag){ String[] s = trim.split("\\s+"); //按照空格切割字符串 for(int j = 0;j<s.length;j++){ System.out.println("判断单词前:"+s[j]); String english = isEnglish(s[j]); System.out.println("输出的单词为:"+ english); char temp = 0 ; if(english != null){ char[] ch = english.tocharArray(); for(int i = ch.length-1;i>=0;i--){ System.out.println(ch[i]); if(ch[i] != ',' && ch[i] != '.'){ sb.append(ch[i]); }else{ temp = ch[i]; } } } if(s[j].contains(",") || s[j].contains(".")){ sb.append(temp); } sb.append(" "); System.out.println("倒叙后单词为:"+ sb.toString()); } } } } /** * 判断是否匹配数字英文字母空格,其中\s代表空格 * @param str * @return */ public static boolean isEnglishNumber(String str){ String regex = "[a-zA-Z0-9,.\\s]+"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(str); if(!m.matches()){ return false; } return true; } /** * 是否匹配单词 * @param english * @return */ public static String isEnglish(String english){ String regex = "[a-zA-Z,.]+"; //匹配单词 Pattern p = Pattern.compile(regex); Matcher matcher = p.matcher(english); /*String word = null; if(matcher.matches()) {// 是否匹配单词 word = matcher.group();// 得到一个单词-树映射的键 } return word;*/ if(!matcher.matches()){ return null; } return english; } }
代码没有经过很多的例子的测试,或许还有很多的不足。原文链接:https://www.f2er.com/javaschema/284862.html