我有一个string类型的变量,我想从中删除所有单个字符。
示例:
String test = "p testing t testing";
我希望输出如下:
String test = "testing testing";
请帮助我。感谢。
答案 0 :(得分:3)
您可能希望使用正则表达式并替换由空格,输入的开头或结尾包围的每个字符,并将其替换为单个空格,例如
String test = "p testing t testing".replaceAll("(^|\\s+)[a-zA-Z](\\s+|$)", " ");
这可能会在字符串的前端和末尾放置一个空格,所以你可能想要单独处理这些情况:
//first replace all characters surrounded by whitespace and the whitespace by a single space
String test = "p testing t testing".replaceAll("\\s+[a-zA-Z]\\s+", " ");
//replace any remaining single character with whitespace and either start or end of input next to it with nothing
test = test.replaceAll("(?>^[a-zA-Z]\\s+|\\s+[a-zA-Z]$)", "");
另一个提示:如果您要过滤任何种字符(即unicode字符),您可能希望将[a-zA-Z]
替换为\p{L}
对于任何字母,[\p{L}\p{N}]
表示任何字母或数字,或\S
表示任何非空格。当然还有更多可能的角色类,所以请查看regular-expressions.info。
最后的说明:
尽管正则表达式是一种“简单”且简洁的解决方法,但对于大输入,它可能比分裂和协调在很大程度上慢。您是否需要这种性能取决于您的需求和输入的大小。
答案 1 :(得分:1)
使用正则表达式可以实现这一点。
试试这个衬垫更换:
字符串测试=" p测试t测试z" .replaceAll(" \\ b [az] \\ b | \\ b [az] \\ b",&# 34;&#34);
答案 2 :(得分:0)
String[] splitString = null;
String test = "p testing t testing";
splitString = test.split(" ");
String newString = "";
for(int i = 0; i < splitString.length; i++)
{
if(splitString[i].length() != 1)
{
newString += splitString[i] + " ";
}
}
newString.trim();
这将遍历拆分字符串并删除长度为1的字符串。
答案 3 :(得分:0)
String[] chunks = test.split("\\s+");
String newtest = new String("");
for ( String chunk : chunks)
{
if (chunk.length() > 1)
{
newtest+= chunk + " ";
}
}
newtest = newtest.trim(); //to remove the last space
答案 4 :(得分:-1)
1.按空格分割字符串。
2.在String数组中检查每个字符串的长度并做出选择。