在Java中查找字符串中的第一个重复单词
示例
import java.util.*;
public class Demo{
static char repeat_first(char my_str[]){
HashSet<Character> my_hash = new HashSet<>();
for (int i=0; i<=my_str.length-1; i++){
char c = my_str[i];
if (my_hash.contains(c))
return c;
else
my_hash.add(c);
}
return '\0';
}
public static void main (String[] args){
String my_str = "thisisasampleonlysample";
char[] my_arr = my_str.toCharArray();
System.out.println("The first repeating character in the string is :");
System.out.println(repeat_first(my_arr));
}
}输出结果
The first repeating character in the string is : I
如果是,则返回该字符,否则将把该字符添加到哈希集中。这样,第二次找到一个单词时,它将被添加到哈希集中,并成为第一个不止一次出现在字符串中的单词。在main函数中,定义了字符串和字符数组。在这个字符数组上调用repeat_first函数。相关数组显示在控制台上。
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短