在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 送给学长毕业祝福语简短