字符串切割问题--文本处理(java)
发布日期:2021-05-07 02:58:38 浏览次数:28 分类:精选文章

本文共 1745 字,大约阅读时间需要 5 分钟。

字符串切割问题–文本处理(java)

题意简述:

  输入一英文文段,从中提取出单词,要求重复的单词被去掉,大写单词全部转化为小写,并且按照字母表的顺序打印输出
  
  
Sample Input

Adventures in Disneyland.Two blondes were going to Disneyland when they came to a fork in theroad. 	The sign read: "Disneyland Left.".So they went home.

Sample output

a adventures blondes came disneyland fork going home in left read sign so the theroad they to two went were when

思路分析:

1.我们从键盘上输入一英文段Scanner.nextLine()包括英文符号,字母和空格都要读入
2.我们要对其进行处理,先将其转为字符数组对数组中的每一个字符判断其是否为字母,如果不是就将其转为空格作为分隔符来切割单词串
3.再将处理好的字符数组转为String的字符串(此时的字符串只有单词和空格两种形式,没有其他的字符了)
4.我们用spilit()函数来利用空格作为分隔符切割字符,后使用TreeSet 结构来存储每个切割的字符串并且转为小写
这里用TreeSet非常重要,因为这个存储的数据结构有很强的优势,一:元素不会重复,为我们省去了去重的时间,二:TreeSet 中的元素会按照自然顺序排好序,让我们能够很好的依次按序输出
5.最后遍历这个TreeSet 我们的结果就出来了

package Exercises;import java.util.*;public class TheSplitOfString {    public static void main(String[] args) {        Scanner s=new Scanner(System.in);        String str1;        str1=s.nextLine();        char[] array=str1.toCharArray();        for (int i = 0; i < array.length; i++) {            if(!Character.isLetter(array[i]))                array[i]=' ';        }        String str2=new String(array);        Set
set=new TreeSet
(); String[] string=str2.split(" "); for (String s1:string) { set.add(s1.toLowerCase()); } for (String s2:set) { System.out.print(s2+" "); } }}

结果测试:

//输入如下Adventures in Disneyland。Two blondes were going to Disneyland when they came to a fork in theroad. The sign read: "Disneyland Left."。So they went home.//输出如下 a adventures blondes came disneyland fork going home in left read sign so the theroad they to two went were when  Process finished with exit code 0

成功!!

Java,我爱的语言,让我们一起学习,一起努力吧!!

上一篇:leetcode-两数之和(简单题-1)
下一篇:缺少的扑克牌【set】

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2025年03月31日 08时13分18秒