Java 创建静态方法以逐字符比较两个字符串。如果字符串a中的所有字母都在字符串b中,则返回true。否则,则返回false
这是到目前为止我的代码。我被卡住了,不知道该怎么办。谢谢你的帮助Java 创建静态方法以逐字符比较两个字符串。如果字符串a中的所有字母都在字符串b中,则返回true。否则,则返回false,java,static,Java,Static,这是到目前为止我的代码。我被卡住了,不知道该怎么办。谢谢你的帮助 public static boolean checkWord(String a, String b){ int x = 0; while (x < a.length()){ int y = 0; while (y < b.length()){ if(a.charAt(x)==b.charAt(y)){ String t = "next";
public static boolean checkWord(String a, String b){
int x = 0;
while (x < a.length()){
int y = 0;
while (y < b.length()){
if(a.charAt(x)==b.charAt(y)){
String t = "next";
System.out.println(t);
y++;
}else{
}
}
x++;
}
return false;
}
公共静态布尔校验字(字符串a、字符串b){
int x=0;
而(x
我还没有编译这段代码,但它应该可以工作
public static boolean checkWord(String a, String b)
{
int j;
for(int i = 0; i < a.length(); i++)
{
j = 0;
while(j < b.length())
{
if(a.charAt(i) == b.charAt(j)) break;
j++;
}
if(j == b.length()) return false;
}
return true;
}
公共静态布尔校验字(字符串a、字符串b)
{
int j;
对于(int i=0;i
据我所知,你想知道“a”中的字母是否以不特定的顺序包含在“b”中,也就是说,你不是在寻找“a”是否是“b”的子字符串
外部循环将遍历字符串a中的每个字符,而内部循环将运行多少次才能发现匹配。如果不匹配,内部循环将其控制变量“j”增加到“b”的大小。这就是为什么要在内部while循环之后进行检查——如果检查通过,这意味着在字符串“b”中的任何位置都找不到字符串“a”中的字母,因此程序可能返回false
如果外部for循环定期结束,则表示所有字母都匹配,函数将返回true。公共静态布尔校验字(字符串a、字符串b){
public static boolean checkWord(String a, String b){
int x = 0;
while (x < a.length()){
int y = 0;
while (y < b.length()){
System.out.println("x:" + x + " y:" + y + " a.charAt(x)==b.charAt(y):" + (a.charAt(x)==b.charAt(y)));
if(a.charAt(x)==b.charAt(y)){
break;
}else{
y++;
}
if (y == b.length()) {
return false;
}
}
x++;
}
return true;
}
int x=0;
而(x
考虑在代码中使用break
。如果在第二个字符串中找不到字符,则应立即返回false。否则,在函数末尾返回true。