求字符串的所有子串-java

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/idealcitier/article/details/82350418

最近看一些编程的题目,字符串的题目有很多,其中关于字符串的子串在很多的题目中都出现了,本文把字符串所有子串的求法总结一下.

java的substring()方法

  • substring

public String substring(int beginIndex,int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
Examples:
"hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"
Parameters:
beginIndex - the beginning index, inclusive.
endIndex - the ending index, exclusive.
Returns:
the specified substring.

思路

使用该方法可以获得单个的字符串,若想获得一个字符串的所有子串,以字符串abbc为例.
abbc的所有的子串为

a
ab
abb
abbc
b
bb
bbc
b
bc
c

代码实现

通过这样规律,获得所有的子串,具体的代码实现如下:

class GetSubstring{
    public static void main(String[] args){
        String str = "abbc";
        System.out.println(str);

        System.out.println("-------------");
        for(int i = 0; i < str.length(); i++){
            for (int j = i+1; j<=str.length(); j++){
                System.out.println(str.substring(i,j));

            }
        }
    }
}

运行上面的代码

java GetSubstring
abbc
-------------
a
ab
abb
abbc
b
bb
bbc
b
bc
c

猜你喜欢

转载自blog.csdn.net/idealcitier/article/details/82350418
今日推荐