Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to ignore spaces in String?

I’m trying do a code where transform a String into a "Dancing string". My code are working but I want ignore spaces " ", how can I do it?

Example:

Scanner input:
Hello Guys

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Output:
Dancing sentence: HeLlO GuYs

I want this output: " HeLlO gUyS"

 import java.util.Scanner;


public class Main {
     String retorno="";
     
    Main(){
    }
String    concatena(String frase){
      String[] split = frase.split("");

    for(int i =0; i<split.length;i++){
         if(i%2==0){
         retorno +=split[i].toUpperCase();
        }
       else 
         retorno +=split[i].toLowerCase();
       }
         return retorno;
    }

    public static void main(String[] args) {
        Main teste = new Main();
        System.out.println("Write the dancing sentence: \n");
       Scanner scanner = new Scanner(System.in);
      teste.concatena(scanner.nextLine());
        System.out.println("Dancing sentence: "+teste.retorno);

    }
}

>Solution :

(i%2==0) doesn’t have a way of considering a space on subsequent iterations, so could introduce a boolean and do something like this:

boolean toUpper = true;
for(int i =0; i<split.length;i++){
    if(split[i].equals(" ")) {
        retorno += split[i];
    } else if (toUpper) {
       retorno +=split[i].toUpperCase();
       toUpper = false;
    } else {
       retorno +=split[i].toLowerCase();
       toUpper = true;
   }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading