0

and thank you for helping me.

So my question is i need a code that asks you for a String like "1234 567" (input), then returns the string numbers like "1 2 3 4 5 6 7" (output) once more my current code is:

public class StringComEspaços {

    public static String formatNumberWithSpaces(String inputString) {
        String outputString = "222";
        return outputString;
    }

    public static void main(String[] args) {
        System.out.println(formatNumberWithSpaces("123 222 2222"));     
    }
}

thanks for the help, and sorry for bad english :).

Pascal Schneider
  • 405
  • 1
  • 5
  • 19
Miguel Ferreira
  • 11
  • 1
  • 1
  • 2
  • Possible duplicate of [Splitting words into letters in Java](http://stackoverflow.com/questions/1521921/splitting-words-into-letters-in-java) – Jagoda Gorus Apr 04 '17 at 10:00
  • 2
    Currently your code doesn't do anything. Did you try to solve your problem on your own first? If yes, what did you achieve? – Pascal Schneider Apr 04 '17 at 11:31
  • 2
    If you want some help it would be better to split the problem in little pieces. Otherwise is like you are using the site for solving your homework, and you won't learn if someone solves it for you. Otherwise if you split the problem in little pieces you have more possibilities to be helped while at the same time will help you to learn. – alphamikevictor Apr 04 '17 at 11:47
  • Yes i did try to solve my problem on my own, but i know 0 about java and im not that good in programming overall, sorry if i gave the impression that i wanted someone to solve my homework, thats why i asked for an explication because i want to undestand what did i do wrong and how can i fix that. – Miguel Ferreira Apr 04 '17 at 13:13

3 Answers3

1

There are many possible ways to solve your problem.

You can do it in an OO way with StringBuilder:

public static String formatNumberWithSpaces(String inputString) {
    StringBuilder output = new StringBuilder();
    for (char c : inputString.toCharArray())     // Iterate over every char
        if (c != ' ')                            // Get rid of spaces
            output.append(c).append(' ');        // Append the char and a space
    return output.toString();
}

Which you can also do with a String instead of the StringBuilder by simply using the + operator instead of the .append() method.

Or you can do it a more "modern" way by using Java 8 features - which in my opinion is fun doing, but not the best way - e.g. like this:

public static String formatNumberWithSpaces(String inputString) {
    return Arrays.stream(input.split(""))        // Convert to stream of every char
                 .map(String::trim)              // Convert spaces to empty strings
                 .filter(s -> !s.isEmpty())      // Remove empty strings
                 .reduce((l, r) -> l + " " + r)  // build the new string with spaces between every character
                 .get();                         // Get the actual string from the optional
}

Just try something that works for you.

Pascal Schneider
  • 405
  • 1
  • 5
  • 19
0

Try out this function:

public static String formatNumberWithSpaces(String inputString){
    String outputString = "";                       //Declare an empty String
    for (int i = 0;i < inputString.length(); i++){  //Iterate through the String passed as function argument
        if (inputString.charAt(i) != ' '){          //Use the charAt function which returns the char representation of specified string index(i variable)
            outputString+=inputString.charAt(i);    //Same as 'outputString = outputString  + inputString.charAt(i);'. So now we collect the char and append it to empty string
            outputString+=' ';                      //We need to separate the next char using ' ' 
            }                                       //We do above instruction in loop till the end of string is reached
    }                           
    return outputString.substring(0, outputString.length()-1);
}

Just call it by:

System.out.println(formatNumberWithSpaces("123 222 2222"));

EDIT:

Or if you want to ask user for input, try:

Scanner in = new Scanner(System.in);
System.out.println("Give me your string to parse");
String input = in.nextLine(); //it moves the scanner position to the next line and returns the value as a string.                 
System.out.println(formatNumberWithSpaces(input)); // Here you print the returned value of formatNumberWithSpaces function

Don't forget to import, so you will be able to read user input :

import java.util.Scanner;

There are various ways to read input from the keyboard, the java.util.Scanner class is one of them.

EDIT2:

I changed:

return outputString;

..to: return outputString.substring(0, outputString.length()-1);

Just because outputString+=' '; was also appending empty space at the end of string, which is useless. Didn't add an if inside for loop which wouldn't add space when last char is parsed, just because of its low performance inside for loop.

Jagoda Gorus
  • 329
  • 4
  • 18
0

use this code.

public class StringComEspaços {

    public static void main(String[] args) {
        System.out.println(formatNumberWithSpaces("123 222 2222"));
    }

    private static String formatNumberWithSpaces(String string) {
        String lineWithoutSpaces = string.replaceAll("\\s+", "");
        String[] s = lineWithoutSpaces.split("");
        String os = "";

        for (int i = 0; i < s.length; i++) {
            os = os + s[i] + " ";
        }
        return os;
    }
}
Pascal Schneider
  • 405
  • 1
  • 5
  • 19
Keyur Bhanderi
  • 1,524
  • 1
  • 11
  • 17