查找字符串中是否有两个特定字符

时间:2014-09-30 08:20:31

标签: java string char substring

我正在做一些java练习,我无法弄清楚为什么答案不是这个。

 for (int i=0;i<str.length()-2;i++)  {
    if ((str.charAt(i)=='b') && (str.charAt(i+2)=='b')) {
    return true; }
    else return false; 
    }
 return false; 

如果给定的字符串(str)中包含“bob”,则问题要求返回true,除了中间字符不需要为“o”。对于字符串三个字符,上面的代码返回true 满足条件的长度,如“bob”或“bbb”,但对于长度大于“bobdfgkabcb”的字符串则为假。我一整天都在努力解决这个问题以及另一个类似的问题,所以我很感激被告知为什么会出错。

感谢。

5 个答案:

答案 0 :(得分:3)

将您的代码更改为:

for (int i=0;i<str.length()-2;i++)  {
    if ((str.charAt(i)=='b') && (str.charAt(i+2)=='b')) {// check 1st and 3rd character, 2nd and 4th character etc
    return true; }
    }
 return false;

或者你可以试试这样的正则表达式:str.matches(".*b[a-zA-Z]b.*")

答案 1 :(得分:0)

你可以使用它:

#!/usr/bin/env python
import os
import zipfile

toDirectory = ".\\Py\Backup"
fileName = int(time.time())

def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file))

if __name__ == '__main__':
    zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)
    zipdir('tmp/', zipf)
    zipf.close()

def fileRename():
    os.renames('Python.zip', fileName + ".zip")

zipdir(toDirectory, ziph) #this is where I am not sure what to do with 'ziph'
fileRename() # Even thought he code create the zip, this does not work

答案 2 :(得分:0)

收到一个字符串错误,所以这是我的解决方法:

public boolean bobThere(String str) {
boolean returner = false;
if(str.contains("bob")){
  return true;
}
for(int i = 0; i < str.length() - 2; i++){
  if(str.charAt(i) == 'b'){
      if(str.charAt(i + 2) == 'b')
       returner = true;
 
  }
}
if(returner == true){
  return returner;
}
return false;
}

如果出现错误,请减去长度减去第二个变量的位置。

答案 3 :(得分:0)

这是一个使用 String 的 indexOf() 方法的实现。

func sample() error {
    tpl, err := template.New("sample").Parse(`<a href="${sticker_set.url}">{{.sticker_set.url}}</a>`)
    if err != nil {
        return err
    }

    data := map[string]interface{}{
        "sticker_set": map[string]interface{}{
            "url": "x",
        },
    }

    if err := tpl.Execute(NoopWriter{}, data); err != nil {
        return fmt.Errorf("Invalid template: %w", err)
    }

    return nil
}

func main() {
    err := sample()
    if err != nil {
        panic(err)
    }
}

答案 4 :(得分:0)

public boolean bobThere(String str) {
    if(str.length()<3)
        return false;
    else {
        for(int i=0;i<str.length()-2;i++){
            if(str.charAt(i)=='b'&&str.charAt(i+2)=='b') return true;
        }
    }
    return false;
}