返回给定字符串中“bread”的第一个和最后一个外观之间的字符串

时间:2015-08-05 17:17:42

标签: java

这个问题来自编码蝙蝠,可能以前曾被问过。请查看代码。

三明治是两片面包之间的东西。返回给定字符串中“bread”的第一个和最后一个外观之间的字符串,如果没有两个面包,则返回空字符串“”。

getSandwich("breadjambread") → "jam"
getSandwich("xxbreadjambreadyy") → "jam"
getSandwich("xxbreadyy") → ""

我的代码是

public static String getSandwich(String str) {
        int ind = str.indexOf("bread");
        int laind = str.lastIndexOf("bread");
        if(!(laind == -1 ))return (str.substring(ind+5,laind)) ;
        return "";
    }

我正在

Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -5 (line number:4)

此输入getSandwich("xxbreadyy")

13 个答案:

答案 0 :(得分:4)

请参阅以下代码

public static String getSandwich(String str) {
    int ind = str.indexOf("bread");
    int laind = str.lastIndexOf("bread");
    if((laind != -1 ) && (ind!=laind))
        return (str.substring(ind+5,laind)) ;
    return "";
}

我在条件中添加(ind!=laind),检查第一个和最后一个“面包”是否相同。

请在此处查看 live demo

答案 1 :(得分:1)

我仅使用一行代码即可与您分享该问题的另一种答案。基本上,使用indexOf()和lastIndexof()可以在检查是否至少有两片面包后找到相应的字符串,并返回两个片之间的子字符串。祝你好运!

public String getSandwich(String str) {
    return  str.matches("(.*bread.*){2}") ? str.substring(str.indexOf("bread")+5,str.lastIndexOf("bread")) : "";    
}

答案 2 :(得分:0)

public class Main {
    public static void main(String aregs[]) {
        String word = "xxbreadyy";
        System.out.println(get(word));
    }

    public static String get(String word) {
        int firstAccurance = getPosition(word);
        System.out.println("first = " + firstAccurance);
        if (firstAccurance != -1 && firstAccurance + 5 < word.length()) {
            String newWord = word.substring(firstAccurance + 5);
            System.out.println("newWord = " + newWord);
            int secondAccurance = getPosition(newWord);
            System.out.println("second = " + secondAccurance);
            if (secondAccurance != -1) {
                return word.substring(firstAccurance+5, secondAccurance+firstAccurance+5);
            } else
                return "";
        } else
            return "";
    }

    private static int getPosition(String word) {
        int i = word.indexOf("bread");
        return i;
    }
}

答案 3 :(得分:0)

失败,因为substring方法的起始索引参数不应大于结束索引。在你的情况下它是7&amp;分别为2。

答案 4 :(得分:0)

Gosh为什么这么多行

public String getSandwich(String str) {
    if (str.length() <= 10) return "";
    return str.substring(str.indexOf("bread")+5,str.lastIndexOf("bread"));
}

答案 5 :(得分:0)

public String getSandwich(String str) 
{
    //if we have something with the minimum amount of characters needed for "bread" + x + "bread",
    //Where x is a string that is not empty.
    if (str.length() >= 11)
    {
      String toTest = "bread";
      String ret = "";
      int counter = 0;
      int wordStart = 0;
      int wordEnd = 0;
      //Test forward for the first "bread" instance.
      for (int i = 5; i < str.length(); i++)
      {
        //If we find the first bread, we set the variable wordStart equal to the place where "bread" ends.
        if (str.substring(i-5, i).equals(toTest))
        {
          wordStart = i;
          //We then test backwards to find the last instance of "bread".
          //And, then we set variable wordEnd where bread begins
          for (int j = 5; j < str.length(); j++)
          {
            if (str.substring(str.length() - j, str.length() - j + 5).equals(toTest))
            {
              wordEnd = str.length() - j;
              break;
            }
          }
          break;
        }
      }
      //We return the substring from the wordStart to the wordEnd
      ret = str.substring(wordStart, wordEnd);
      return ret;
    }
    else
    {
      return "";
    }
  }

答案 6 :(得分:0)

以下是我不使用indexof关键字的答案:

public String getSandwich(String str) {
    int beforestf = 0;
    int endstf = 0;
    String stf;
    for (int i = 0; i <= str.length() - 5; i++) {
        if (str.substring(i, i + 5).equals("bread")) {
            endstf = i;
        }
    }
    for (int j = str.length(); j >= 5; j--) {
        if (str.substring(j-5, j).equals("bread")) {
            beforestf = j;
        }
    }
    if ((endstf>=5))stf=str.substring(beforestf,endstf);
    else stf="";

    return stf;
}

答案 7 :(得分:0)

public String getSandwich(String str) 
{
  String s="bread";
  //To have a string in between "bread" ideal string length should be greater than 10 i.e., BreadBread=Length(10)!!
  if(str.length()>10 && str.substring(str.indexOf(s)+5,str.lastIndexOf(s)).length()>0)
    return str.substring(str.indexOf(s)+5,str.lastIndexOf(s));    

  return "";  

}

答案 8 :(得分:0)

这是另一种类似的方法,而不是使用两个for循环来获取第一个面包和第二个面包的索引:

public String getSandwich(String str) {
  int bread1= str.indexOf("bread");
  int bread2= 0;
  for(int i=str.length()-1;i>=0;i--){
    if(str.charAt(i)=='d'&&str.charAt(i-1)=='a'&&str.charAt(i-2)=='e'&&str.charAt(i-3)=='r'&&str.charAt(i-4)=='b'){
      bread2 = i-4;
      if(bread1!=bread2)
        return str.substring(bread1+5,bread2);
    }
  }
    return "";  
}

答案 9 :(得分:0)

这是我的解决方案,它传递了CodingBat中的所有测试:

 public String getSandwich(String str) {
    String bread = "bread";

     int lIndex = str.indexOf(bread);
     int rIndex = str.lastIndexOf(bread);

      if(lIndex != -1 && rIndex != lIndex){
          return str.substring(lIndex + bread.length(), rIndex);
      }
      return "";
   }

答案 10 :(得分:0)

我递归地解决了这个问题,并且没有像这样使用内置的indexOf内置Java字符串方法:

public String getSandwich(String str) {
    final String BREAD = "bread";
    if(str.length() < BREAD.length() * 2){
        return "";
    }
    if(str.substring(0, BREAD.length()).equals(BREAD) && 
        str.substring(str.length() - BREAD.length()).equals(BREAD)){
        return str.substring(BREAD.length(), str.length() - BREAD.length());
    }
    if(! str.substring(0, BREAD.length()).equals(BREAD)){
        return getSandwich(str.substring(1));
    }
    return getSandwich(str.substring(0, str.length() - 1));
}

答案 11 :(得分:0)

public String getSandwich(String str) {

  int a = str.indexOf("bread");

  int b = str.lastIndexOf("bread");

  return b-a> 4 ?str.substring(a+5,b): "";

}

答案 12 :(得分:0)

public String getSandwich(String str) {
    String g = "";
    int temp = str.indexOf("d");
    int  count=str.lastIndexOf("bread");

    if(!(str.contains("bread"))) {
        return g;
    }

    for(int i= temp+1;i<count;i++) {
        g = g + str.charAt(i);
    }
    return g;
}