求字符串的所有子串-java

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

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
  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值