计算字符串的子字符串

时间:2019-03-07 15:03:28

标签: java

public class Test {
    public static void main(String[] args) {
        System.out.println(countHi("xhixhxihihhhi"));
    }
    public static int countHi(String str) {
        if( str.length() < 2 ) return 0;
        if ( str.indexOf("hi") == -1 ) {
            return 0;
        }
        if ( str.length() == 2 ) {
            if ( str.indexOf("hi") == 0 ) return 1;
            return 0;
        }
        int i = str.indexOf("hi");
        return 1 + countHi( str.substring(0,i) + str.substring(i+1, str.length()));
    }

}

有人可以向我解释为什么“ hi”出现的结果是5而不是3?

2 个答案:

答案 0 :(得分:1)

因为您要进行递归

const data = {
  'one': ['hello\nworld', 'java\nscript'],
  'two': ['hi\nworld', 'java\nscript\nis\nawesome']
};

const html = Object.values(data).flat().map(e => e.replace('\n', '<br />')).join(' ');

document.body.innerHTML += html;

不只是

services:
  orient-db-1:
    image: orientdb:3.0.1
    entrypoint: /orientdb/bin/server.sh -Ddistributed=true
    environment:
      ORIENTDB_ROOT_PASSWORD: root
    volumes:
      - /data/orient_db/1/=/orientdb/databases

  orient-db-2:
    image: orientdb:3.0.1
    entrypoint: /orientdb/bin/server.sh -Ddistributed=true
    environment:
      ORIENTDB_ROOT_PASSWORD: root
    volumes:
      - /data/orient_db/2/=/orientdb/databases

  orient-db-3:
    image: orientdb:3.0.1
    entrypoint: /orientdb/bin/server.sh -Ddistributed=true
    environment:
      ORIENTDB_ROOT_PASSWORD: root
    volumes:
      - /data/orient_db/3/=/orientdb/databases

,并且由于初始字符串包含多个str.substring(0,i) + str.substring(i+1, str.length()) ,因此您将创建开始时不存在的新str.substring(i+1, str.length())
更改为此:

h

答案 1 :(得分:-1)

使用Apache Commons lang解决问题的简便方法。试试这个。

public class Test {
    public static void main(String[] args) {
        System.out.println(countHi("xhixhxihihhhi"));
    }
    public static int countHi(String str) {
        return StringUtils.countMatches(str, "hi");     
    }
}

如果您使用Spring,那么..

public class Test {
    public static void main(String[] args) {
        System.out.println(countHi("xhixhxihihhhi"));
    }
    public static int countHi(String str) {
        return StringUtils.countOccurrencesOf(str, "hi");     
    }
}