zoukankan      html  css  js  c++  java
  • Day_12【集合】扩展案例2_键盘录入一个字符串,对其进行去重,并将去重后的字符串组成新数组

    需求分析:键盘读取一行输入,去掉其中重复字符, 打印出不同的那些字符

    •  思路:
       	1.键盘录入字符串
       	2.遍历字符串,将每个字符存储到集合中
       	3.将集合中重复的字符去掉
       	4.创建新集合,遍历老集合,获取老集合中的元素,判断新集合中是否包含这个元素
       		a)如果不包含,则将这个元素添加到新集合中
       	5.清空老集合中元素
       	6.将新集合中的元素添加到老集合中
       	7.遍历老集合
      

    代码

    package com.itheima;
    
    import java.util.ArrayList;
    import java.util.Scanner;
    
    public class Test2 {
    	public static void main(String[] args) {
    		//创建键盘录入对象
    		Scanner sc = new Scanner(System.in);
    		
    		System.out.println("请输入一行字符串:");
    		String str = sc.nextLine();
    		
    		//将字符串转换为数组
    		char[] chs = str.toCharArray();
    		
    		//创建集合对象
    		ArrayList<Character> list = new ArrayList<Character>();
    		
    		//遍历char集合,并将不重复的元素添加到新集合中
    		for(char ch : chs){
    			if(!list.contains(ch)){
    				list.add(ch);
    			}
    		}
    		
    		//定义新数组
    		char[] newChs = new char[list.size()];
    		//定义新集合的索引
    		int index = 0;
    		//遍历集合
    		for(char ch : list){
    			newChs[index++] = ch;
    		}
    		System.out.println(newChs);
    	}
    }
    
    

    控制台输出内容
    console

  • 相关阅读:
    Docker PHP 扩展配置
    PHP 打水印功能
    MYSQL的主从复制
    CentOS7开启防火墙及特定端口
    非常全面的讲解Hosts文件
    STL的erase()陷阱-迭代器失效总结
    scons使用
    SecureCRT 使用技巧
    atomic, spinlock and mutex性能比较
    内存池的实现(二)
  • 原文地址:https://www.cnblogs.com/zzzsw0412/p/12772525.html
Copyright © 2011-2022 走看看