英文:
Check a string to see if 2 letters are found next to each other in the string
问题
public class AB
{
public static boolean check(String s, String a, String b)
{
for (int i = 0; i < s.length() - 1; i++) {
if (s.substring(i, i + 1).equals(a) && s.substring(i + 1, i + 2).equals(b)) {
return true;
}
}
return false;
}
}
public class AplusRunner
{
public static void main(String args[])
{
System.out.println(AB.check("chicken", "a", "b"));
System.out.println(AB.check("frog", "f", "g"));
System.out.println(AB.check("chicken ", "c", "k"));
System.out.println(AB.check("apluscompsci ", "a", "s"));
System.out.println(AB.check("apluscompsci ", "a", "p"));
System.out.println(AB.check("apluscompsci ", "s", "c"));
System.out.println(AB.check("apluscompsci ", "c", "p"));
}
}
英文:
I need to figure out how to determine true or false if 2 specific letters in a string are right next to each other.
For example: In AplusRunner the System.out.println(AB.check("frog","f","g"));
should return false because the letters "f" and "g" are not right next to each other.
System.out.println(AB.check("chicken","c","k"));
should return true since "c" and "k" are right next to each other.
All I need help with is how to determine if a string contains two letters right next to each other or not. Thanks
public class AB
{
public static boolean check( String s, String a, String b)
{
}
}
public class AplusRunner
{
public static void main( String args[] )
{
System.out.println( AB.check( "chicken", "a", "b" ) );
System.out.println( AB.check( "frog", "f", "g" ) );
System.out.println( AB.check( "chicken ", "c", "k" ) );
System.out.println( AB.check( "apluscompsci ", "a", "s" ) );
System.out.println( AB.check( "apluscompsci ", "a", "p" ) );
System.out.println( AB.check( "apluscompsci ", "s", "c" ) );
System.out.println( AB.check( "apluscompsci ", "c", "p" ) );
}
}
</details>
# 答案1
**得分**: 3
我会在这里使用 `String#contains`:
```java
public static boolean check(String s, String a, String b) {
return s.contains(a + b);
}
英文:
I would use String#contains
here:
public static boolean check(String s, String a, String b) {
return s.contains(a + b)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论