Loop to remove characters from string one by one

Hello I´d like to know a way to "remove" the characters of a string and print it. For example: So far I was able to do the oposite:

    String str = "SUNDAY";
    StringBuilder sb = new StringBuilder(str.length());

    for (char c : str.toCharArray()) 
    {
        sb.append(c);
        System.out.println(sb);
    }

STRING = "SUNDAY"

SUNDAY

SUNDA

SUND

SUN

SU

S

Upvotes: 0

Views: 452

Answers (3)

Mushif Ali Nawaz
Mushif Ali Nawaz

Reputation: 3866

Here is a bit tricky IntStream version:

IntStream.range(0, s.length()).map(i -> s.length() - i).mapToObj(i -> s.substring(0, i)).forEach(System.out::println);

Upvotes: 0

seenukarthi
seenukarthi

Reputation: 8624

You don't actually need a StringBuilder to print sub string of your String.

You have to have a loop which will start at the loop counter at the length of the string and end at the counter is at 1 the counter should decrements at each loop. Use the counter as the as the end index in String.substring(beginindex,endindex)

String str = "SUNDAY";
for (int i = str.length(); i > 0; i--) {
    System.out.println(str.substring(0, i));
}

Upvotes: 1

hiren
hiren

Reputation: 1105

This might do it for you:

String s = "SUNDAY";
int j = s.length();
for (int i = 0; i < s.length(); i++, j--) {
    System.out.println(s.substring(0, j));
}

Upvotes: 1

Related Questions