没有合适的资源?快使用搜索试试~ 我知道了~
编写程序,输入两段文字,自动找出两段文字中相同的文字 提示把输入的两段文字转换为集合,然后运用集合的交集运算即可输出相同的文
需积分: 1 0 下载量 152 浏览量
2024-05-10
11:35:54
上传
评论
收藏 14KB DOCX 举报
温馨提示
试读
1页
编写程序,输入两段文字,自动找出两段文字中相同的文字。【提示】把输入的两段文字转换为集合,然后运用集合的交集运算即可输出相同的文字。
资源推荐
资源详情
资源评论
编写程序,输入两段文字,自动找出两段文字中相同的文字。 【提示】把输入的两段文字
转换为集合,然后运用集合的交集运算即可输出相同的文字。 java 代码实现示例:
import java.util.HashSet;
import java.util.Set;
public class CommonWordsFinder {
public static void main(String[] args) {
String text1 = "This is a sample text.";
String text2 = "Another sample text.";
Set<String> words1 = extractWords(text1);
Set<String> words2 = extractWords(text2);
Set<String> commonWords = findCommonWords(words1, words2);
System.out.println("Common words:");
for (String word : commonWords) {
System.out.println(word);
}
}
private static Set<String> extractWords(String text) {
Set<String> words = new HashSet<>();
String[] tokens = text.split("\s+"); // Split by whitespace
for (String token : tokens) {
// Remove punctuation and convert to lowercase for consistency
String word = token.replaceAll("[^a-zA-Z]", "").toLowerCase();
words.add(word);
}
return words;
}
private static Set<String> findCommonWords(Set<String> words1, Set<String> words2)
{
Set<String> commonWords = new HashSet<>(words1);
commonWords.retainAll(words2);
return commonWords;
}
}
资源评论
射手座的程序媛
- 粉丝: 1702
- 资源: 149
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功