Home > database >  How would I modify my code to delete chars from the beginning?
How would I modify my code to delete chars from the beginning?

Time:05-08

So instead of starting from the last index I would like it to do the opposite where it would start removing the start of the string (first index).

public class Sample 
{ 
  public static void main(String[] args) 
  {        
    char y[] = {'L','E','M','O','N','A','D','E'};

    int x = y.length;      
    for (int z = 0; z < len; z  )
    {           
      for(int w = 0; w < len - z; w  )
      {          
        System.out.print(word[w]);             
      }        
    }       
  }   
}

So the output of this code would be:

LEMONADE
LEMONAD
LEMONA
LEMON
LEMO
LEM
LE
L

What I would like is the opposite this time, it would start from the starting index

Example:

LEMONADE
EMONADE
MONADE
ONADE
NADE
ADE
DE
D

Please help me with the code I've provided

CodePudding user response:

Here is the code for your answer. This should work for you.

public class MyClass {
   public static void main(String[] args) { 
        char y[] = {'L','E','M','O','N','A','D','E'};
        int len = y.length;
        for (int z = 0; z < len; z  ){
            for(int w = z; w < len; w  ){
                System.out.print(y[w]);
            }
            System.out.println();
        }   
    }
}

CodePudding user response:

    char y[] = {'L', 'E', 'M', 'O', 'N', 'A', 'D', 'E'};
    String lemonade = String.valueOf(y);
    for (int i = 0; i < lemonade.length(); i  ) {
        if (i   1 == lemonade.length()) {
            System.out.println(lemonade.substring(i - 1, lemonade.length() - 1));
        } else {
            System.out.println(lemonade.substring(i, lemonade.length()));
        }
    }

CodePudding user response:

public class Driver {
  public static void main(String[] args) {

    char y[] = {'L', 'E', 'M', 'O', 'N', 'A', 'D', 'E'};

    for (int i = 0; i < y.length; i  ) {
        StringBuilder word = new StringBuilder();
        for (char c:
             getCharactersFromIndexAndBeyond(y, i)) {
            word.append(c);
        }
        System.out.println(word.toString());
    }
}
  static char[] getCharactersFromIndexAndBeyond(final char[] inputArray, final int indexToStartAfter){
    char[] outputArray = new char[inputArray.length - indexToStartAfter];
    int count = 0;
    for(int i = indexToStartAfter; i < inputArray.length; i  ){
        outputArray[count] = inputArray[i];
        count  ;
    }
    return outputArray;
}

}

The code above should work, provided you made a typo in your desired output DE D should be DE E

Disclaimer:

I would not use this solution compared to the others that are posted here, but it takes a more drawn-out approach to highlight what is happening.

CodePudding user response:

String text="LEMONADE";

int length=text.length();
for(int i=0;i<length;i  )
  System.out.println(text.substring(i));
  • Related