Eric Dants
Eric Dants

Reputation: 31

I want to print all letters except the last one, then the last two, then the last 3

I'm trying to print a string like this:

cat
ca
c

But with my code now, I'm only getting

ttt
tt
t

code

public static String bingo(String s) {
        int len = s.length();
        for(int i = 1; i <=s.length(); i++) {
            for(int k = 1; k <= s.length() - i+1; k++) {
                System.out.print(s.substring(len-5));
            }
            System.out.println();
        }
        return s;
    }

Upvotes: 1

Views: 634

Answers (5)

omkar
omkar

Reputation: 1

please find below mentioned solution

public String bingo(String s) {
    //if input is 'cat'(s=cat)
    int len = s.length();
    String data = null;
    for (int i = 0; i < len; i++) {

        if (i == 0) {
            data = s.substring(0, len - i);
        } else {
            data = data + " " + s.substring(0, len - i);
        }

    }
    //getting output as 'cat ca c'
    return data;
}

Upvotes: 0

josejuan
josejuan

Reputation: 9566

Of course the other answers are correct, but why not also learn in a functional way?

// you can use the tails everywhere you need (require Java 9+)
static Stream<String> tails(String xs) {
    return Stream.iterate(xs, x -> !x.isEmpty(), x -> x.substring(0, x.length() - 1));
}

// usage example
public static void main(String[] args) {
    tails("cat").forEach(System.out::println);
}

The parameters are self-explanatory (see javadoc iterate) however:

.iterate(                                       // iterate
        xs,                                     // using `xs` as seed
        x -> !x.isEmpty(),                      // as long as the condition is true
        x -> x.substring(0, x.length() - 1)     // transform the current value
);

Upvotes: 1

Ilya Sereb
Ilya Sereb

Reputation: 2571

You almost got it!

This is how it could be done with while loop.

public static String bingo(String s) {

    int index = s.length();
    while (index != 0)
        System.out.println(s.substring(0, index--));

    return s;
}

This is how it could be done with for loop

public static String bingo(String s) {
    for (int i = s.length(); i != 0; i--)
        System.out.println(s.substring(0, i));
    return s;
}

Upvotes: 1

Dani Mesejo
Dani Mesejo

Reputation: 61920

You could iterate from the length to 1 and print the sub-string in each line:

public static void bingo(String s) {
    for (int i = s.length(); i > 0; i--) {
        System.out.println(s.substring(0, i));
    }
}

Output (for cat)

cat
ca
c

Upvotes: 2

SSP
SSP

Reputation: 2670

public static String bingo(String s) {
    int len = s.length();
    for(int i = 0; i <s.length(); i++) {
            System.out.println(s.substring(0,len-i));
    }
    return s;
}

Upvotes: 0

Related Questions