Adrija
Adrija

Reputation: 71

Returning a substring from a method using java

Is there a way of returning substring from a string in java? For example if I have a string:aadaa It should return me: {a,a,d,a,a,aa,ad,aa,aad,ada,daa..} This is my code:

String substring(String str1)
{ 
    //String sbs="";
    int len=str1.length();

    for (int i=0;i<len;i++)
    {
        for (int j=i+1;j<=len;j++)
        {
            return(str1.substring(i, j));

        }

    }

I need the return statement to return a value from this method not to print it. Please help.

Upvotes: 1

Views: 259

Answers (2)

Trần Nam Trung
Trần Nam Trung

Reputation: 113

As oRole's answer, if you don't want duplicate values, simply change List to HashSet. Since Java Set doesn't hold duplicate values.

public static HashSet<String> GetSubstrings(String str) {

    // set up any substring and add it to the ArrayList
    HashSet<String> subStrings = new HashSet();
    for (int i = 0; i < str.length(); ++i) {
        for (int j = 1; j <= str.length() - i; ++j) {
            subStrings.add(str.substring(i, i + j));
        }
    }

    return subStrings;
}

Upvotes: 1

oRole
oRole

Reputation: 1346

To get all substrings of a given String using Java, you can use this GetSubtrings method:

public static ArrayList<String> GetSubstrings(String str) {

    // set up any substring and add it to the ArrayList
    ArrayList<String> subStrings = new ArrayList();
    for (int i = 0; i < str.length(); ++i) {
        for (int j = 1; j <= str.length() - i; ++j) {
            subStrings.add(str.substring(i, i + j));
        }
    }

    return subStrings;
}

An example on how to use it would be:

// stores all substrings
ArrayList<String> subStrings = new ArrayList();

// call method to get all substrings
subStrings = GetSubstrings("Test");

This will return an ArrayList which contains: { "T", "Te", "Tes", "Test", "e", "es", "est", "s", "st", "t" }

Whole example program:

package com.company;

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

        // stores all substrings
        ArrayList<String> subStrings = new ArrayList();

        // call method to get all substrings
        subStrings = GetSubstrings("Test");
    }    

    public static ArrayList<String> GetSubstrings(String str) {

        // set up any substring and add it to the ArrayList
        ArrayList<String> subStrings = new ArrayList();
        for (int i = 0; i < str.length(); ++i) {
            for (int j = 1; j <= str.length() - i; ++j) {
                subStrings.add(str.substring(i, i + j));
            }
        }

        return subStrings;
    }
}

Upvotes: 2

Related Questions