java - StringUtils 问题。如何修复此字符串字母检查?
问题描述
此代码从用户那里获取一个输入字符串,其中可能包含特殊字符。然后我们输出字母表中缺少的字母。例如,“the quick brown fox jumped over the lazy dog”将返回一个空字符串,但“ZYXW, vu TSR Ponm lkj ihgfd CBA”。会缺少字母“eq”。
目前,我的程序正在返回整个字母表,而不仅仅是丢失的字符。
import java.io.*;
import org.apache.commons.lang3.*;
public class QuickBrownFox {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
s = s.toUpperCase();
String[] arr = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S",
"T", "U", "V", "W", "X", "Y", "Z" };
String chars_only = "";
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < arr.length; j++) {
if (s.substring(i, i + 1).equals(arr[j])) {
chars_only += s.substring(i, i + 1);
}
}
}
System.out.println(chars_only); // now we have a string of only alphabet letters
String missing = "";
for (int j = 0; j < arr.length; j++) {
if (StringUtils.contains(arr[j], chars_only) == false) { // alphabet letter not found
missing += arr[j];
}
}
missing = missing.toLowerCase();
System.out.println("missing letters: " + missing);
}
}
解决方案
一种选择是使用Set
用给定的初始化alphabet-chars
。然后从set
任何chars
包含在input-string
. 余数将反映缺失chars
。
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class TestAlphabet {
public static void main(String[] args) {
Set<Character> set = new HashSet<Character>();
Character[] arr = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
Collections.addAll(set, arr);
String s1="abc";
System.out.println("input:"+s1);
new TestAlphabet().new Missing().getMissing(set, s1).forEach(System.out::print);
System.out.println("\n");
String s2="the quick brown fox jumped over the lazy dog";
System.out.println("input:"+s2);
new TestAlphabet().new Missing().getMissing(set, s2).forEach(System.out::print);
System.out.println("\n");
String s3="ZYXW, vu TSR Ponm lkj ihgfd CBA.";
System.out.println("input:"+s3);
new TestAlphabet().new Missing().getMissing(set, s3).forEach(System.out::print);
}
class Missing
{
public Set<Character> getMissing(Set<Character> orig, String s)
{
//keep origin
Set<Character> set = new HashSet<Character>();
set.addAll(orig);
s=s.toUpperCase();
for(int i=0;i<s.length();i++)
{
Character c=s.charAt(i);
set.remove(c);
}
return set;
}
}
}
输出
input:abc
DEFGHIJKLMNOPQRSTUVWXYZ
input:the quick brown fox jumped over the lazy dog
S
input:ZYXW, vu TSR Ponm lkj ihgfd CBA.
EQ
推荐阅读
- python - 如何在django rest框架的ListCreateApiView中使用create函数而不是perform_create
- jenkins - 在 Jenkins Pipeline 的 HTML 正文中使用环境变量
- arrays - 如何在C中初始化数组?
- matrix - 将每一列除以最大值/最后一个值
- eclipse - Apache Tomcat 9.0.40 服务器在 eclipse 上运行时抛出 404 错误。否则它工作正常
- google-cloud-platform - BigQuery 摘要
- wordpress - 如何更改 wordpress 网站上的默认单词?
- java - 分数计算
- rust - 无法将 Struct 属性设置为 Enum Rust
- python - 在 python 中使用 ECB、CBC 和 CFB 模式加密图像时出现错误“IV 没有意义”