我有以下代码可以选择找到彼此相邻的任意两个字母并删除一个。
例如:singleOccurrence("1//2/2018")
我的代码:
public static StringBuilder singleOccurrence(String s) {
StringBuilder sb = new StringBuilder();
if (s.length() > 0) {
char prev = s.charAt(0);
sb.append(prev);
for (int i = 1; i < s.length(); ++i) {
char cur = s.charAt(i);
if (cur != prev) {
sb.append(cur);
prev = cur;
}
}
}
return sb;
}
这将返回:&#34; 1/2/208&#34;
但是,如果我输入了:singleOccurrence("11//2/2018")
它将返回:&#34; 1/2/208&#34;
请注意,我的方法会删除所有字符的两次出现。
我的问题是如何让我的方法只做它应该对字符"/", "-", ":"
提前致谢:)
答案 0 :(得分:1)
将此添加到if语句中。检查是否普遍&amp; cur字符不是&#39; - &#39; &#39; /&#39;或者&#39;:&#39;附加到结果。
{
"_id" : ObjectId("5a80993f32fcc2489f995aaf"),
"username" : "uname",
"password" : "pass",
"email" : "test@mail.com"
}
答案 1 :(得分:1)
public void singleOccurrence(String string)
{
char[] chars = string.toCharArray();
List<Character> characters = new ArrayList<>();
char temp = 0;
for (char c : chars) {
if (temp != c || (c != '/' && c != '_' && c != ':')) {
characters.add(c);
}
temp = c;
}
StringBuilder sb = new StringBuilder();
for (Character character : characters) {
sb.append(character);
}
Log.e(TAG, sb.toString());
}
希望它可以帮到你!