检查一个字符串,看看是否在字符串中有2个字母是连在一起的。

huangapple go评论70阅读模式
英文:

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(&quot;frog&quot;,&quot;f&quot;,&quot;g&quot;)); should return false because the letters "f" and "g" are not right next to each other.

System.out.println(AB.check(&quot;chicken&quot;,&quot;c&quot;,&quot;k&quot;)); 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( &quot;chicken&quot;, &quot;a&quot;, &quot;b&quot; ) );
		System.out.println( AB.check( &quot;frog&quot;, &quot;f&quot;, &quot;g&quot; ) );
		System.out.println( AB.check( &quot;chicken &quot;, &quot;c&quot;, &quot;k&quot; ) );
		System.out.println( AB.check( &quot;apluscompsci &quot;, &quot;a&quot;, &quot;s&quot; ) );
		System.out.println( AB.check( &quot;apluscompsci &quot;, &quot;a&quot;, &quot;p&quot; ) );
		System.out.println( AB.check( &quot;apluscompsci &quot;, &quot;s&quot;, &quot;c&quot; ) );
		System.out.println( AB.check( &quot;apluscompsci &quot;, &quot;c&quot;, &quot;p&quot; ) );
      		
	}
}


</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)
}

huangapple
  • 本文由 发表于 2020年9月27日 16:26:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/64086398.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定