英文:
i want to remove 'a' and 'b' from the string but whole string will print in the end, why?
问题
public class Test {
public static void main(String[] args) {
String st = "abracadabra";
String newst = "";
int len = st.length();
for (int i = 0; i < len; i++) {
char ch = st.charAt(i);
if (ch != 'a' || ch != 'b') {
newst = newst + ch;
}
}
System.out.println(newst);
}
}
英文:
I want to remove 'a' and 'b' from the string but the whole string will print in the end, I do not understand what is happening in this code because the code will run properly when I use other methods.
public class Test
{
public static void main(String[] args)
{
String st = "abracadabra";
String newst = "";
int len = st.length();
for(int i=0; i<len; i++)
{
char ch = st.charAt(i);
if(ch!='a' || ch!='b')
{
newst= newst+ ch;
}
}
System.out.println(newst);
}
}
答案1
得分: 0
你可以使用以下代码来替代循环遍历字符串并替换其中的a和b:
String st = "abracadabra";
st = st.replaceAll("[ab]", "");
System.out.println(st);
输出结果为:
rcdr
英文:
you can do this instead of looping through string to replace a and b from your string:
String st = "abracadabra";
st = st.replaceAll("[ab]", "");
System.out.println(st);
Output is :
rcdr
答案2
得分: 0
public class Test {
public static void main(String[] args) {
String st = "abracadabra";
String newst = "";
int len = st.length();
for (int i = 0; i < len; i++) {
char ch = st.charAt(i);
if (ch != 'a' && ch != 'b') {
System.out.println(ch);
}
}
System.out.println(newst);
}
}
英文:
public class Test
{
public static void main(String[] args)
{
String st = "abracadabra";
String newst = "";
int len = st.length();
for(int i=0; i<len; i++)
{
char ch = st.charAt(i);
if(ch!='a' && ch!='b')
{
System.out.println(ch);
}
}
System.out.println(newst);
}
}
答案3
得分: -1
if(ch!='a' && ch!='b')
英文:
if(ch!='a' || ch!='b')
... should be
if(ch!='a' && ch!='b')
专注分享java语言的经验与见解,让所有开发者获益!
评论