java中如何提取多个字符串相同的字符

代码如下:

 

 

 

 

package com.hp.test;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * 提取多个字符串相同的字符
 * @author HP
 *
 */
public class StringTest{
    
	/**
	 * 提取相同字符
	 * abc   a b c
	 * bcd   b c d
	 * cde   c d e
	 * @param list
	 * @return
	 */
	public static LinkedHashSet<Character> getCommonChar(List<String> list){
		//创建结果集合
		LinkedHashSet<Character> resultList = new LinkedHashSet<>();
		//对数据进行处理
        if(list != null && list.size()>0){//集合不为空    	  
    	    //创建集合
    	    LinkedHashSet<Character> charList  = new LinkedHashSet<>();
     	    for (String string : list) {//循环集合
 				char[] charArray = string.toCharArray();
 				for (char c : charArray) {
					 charList.add(c);
				}
 			} 
    	   //对全部字符去重,去重结果即为公共元素
     	   resultList.addAll(charList);
     	   System.out.println(charList);
     	   LinkedHashSet<Character> temp  = new LinkedHashSet<>();//中间集合
     	   LinkedHashSet<Character> other  = new LinkedHashSet<>();//不是公共字符的集合
           for (String string : list) {
        	   char[] charArray = string.toCharArray();
        	   //移除
			   for (char c : charArray) {
					charList.remove(c);
			   }
			   //中间交互值
			   temp.addAll(charList);//得到去除后的集合
			   other.addAll(temp);//添加到不是公共字符里
			   System.out.println(temp+"--------------");
			   charList.addAll(resultList);
			   System.out.println(charList+"*********");
			   temp.clear();//清空中间集合	
			   System.out.println("--------------------------------");
		   }
           // 去除不是公共的字符
     	   resultList.removeAll(other);
     	 
       }
        System.out.println("结果为:"+resultList);
		//返回公共字符
		return resultList;
	}
	
	public static void main(String[] args) {
		List<String> list = new ArrayList<>();
		list.add("abc");
		list.add("bcd");
		list.add("cde");		
		getCommonChar(list);
	}
}

 

 

 

执行结果如下:

 

 

 

[a, b, c, d, e]
[d, e]--------------
[d, e, a, b, c]*********
--------------------------------
[e, a]--------------
[e, a, b, c, d]*********
--------------------------------
[a, b]--------------
[a, b, c, d, e]*********
--------------------------------
结果为:[c]
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

 

 

分析:

         1.当传入多个字符串时就不能简单的像俩个字符串提取一样,必须要转换思路,也就是先把所有的字符保存到一个总的集合里面,

         2.对字符串集合遍历,对每个字符串进行去重操作,之所以进行去重,是因为如果一个字符串都不包含这个字符,那么这个字符一定不是公共字符,

         3.用总的字符集合,减去不是公共字符的总集合,得到公共字符总集合.

       
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值