简体   繁体   中英

How do I take an input and make the program print out each letter on a new line while making every space encounter to print out “<space>”?

import java.util.Scanner;

public class TwoDotSevenNumbaTwo {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String input;
        int num1, num2, leng;
        char word;
        Scanner inputscan = new Scanner(System.in);
        System.out.println("Give me some love baby");
        input = inputscan.nextLine();
        leng = input.length();
        num1 = 0;
        num2 = 1;

        while (num1 < leng) {
            input = input.replaceAll(" ", "<space>");
            System.out.println(input.charAt(num1));

            num1++;
        }
    }
}

I can't seem to figure out how to get the <space> on a single line. I know I can't do it because it is a char but I can't find a way around it.

You could do

for(int i = 0; i < leng; ++i) {
   char x = input.charAt(i);
   System.out.println(x == ' ' ? "<space>" : x);
}

Once you've stored the input as a String, you can write:

// Break the string into individual chars
for (char c: input.toCharArray()) {
    if (c == ' ') { // If the char is a space...
        System.out.println("<space>");
    }
    else { // Otherwise...
        System.out.println(c);
    }
}

Regex powa:

yourText.replaceAll(".", "$0\n").replaceAll(" ","<space>");

Explanation:

First replaceAll takes every charachter ( . = any character) and replaces it with the same character ( $0 = matched text) followed by a newline \\n , thusly every character is on separate line.

Second replaceAll just replaces every acctual space with the word "<space>"

For java regex tutorial, you can follow this link or use your favourite search engine to find plenty more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM