【问题标题】:Java String With Spaces带空格的 Java 字符串
【发布时间】:2017-08-29 10:58:33
【问题描述】:

谢谢你帮助我。

所以我的问题是我需要一个代码来询问您输入“1234 567”(输入)之类的字符串,然后再次返回“1 2 3 4 5 6 7”(输出)之类的字符串数字 我当前的代码是:

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"));     
    }
}

感谢您的帮助,抱歉英语不好:)。

【问题讨论】:

  • 目前你的代码没有做任何事情。您是否尝试过自己先解决问题?如果是,你取得了什么成就?
  • 如果您需要一些帮助,最好将问题分成小块。否则就像您正在使用该网站来解决您的家庭作业,如果有人为您解决它,您将不会知道。否则,如果你把问题分成小块,你就有更多的机会得到帮助,同时也会帮助你学习。
  • 是的,我确实尝试过自己解决我的问题,但我对 java 的了解为 0,而且我在整体编程方面不是那么好,对不起,如果我给人的印象是我希望有人来解决我的作业,这就是为什么我要求解释,因为我想不明白我做错了什么以及如何解决这个问题。

标签: java string numbers spaces


【解决方案1】:

试试这个功能:

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);
}

只需通过以下方式调用它:

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

编辑:

或者如果你想询问用户输入,试试:

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

不要忘记导入,这样您就可以读取用户输入:

import java.util.Scanner;

从键盘读取输入的方法有很多种,java.util.Scanner 类就是其中之一。

编辑2:

我变了:

return outputString;

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

仅仅因为outputString+=' ';还在字符串末尾附加了空格,这是没用的。没有在for 循环中添加if,它在解析最后一个字符时不会添加空间,只是因为它在for 循环中的性能较低。

【讨论】:

  • 记住接受一个在这里非常重要的答案。很高兴我能帮上忙。
  • 再次感谢你,如果不是问你太多,你能解释一下这个功能是如何工作的吗?
  • 您应该将变量命名为 outputString 以匹配命名约定和一致的代码(适合您的方法的参数)
  • @PascalSchneider 我解决了这个问题,感谢您指出这一点 :) 我还添加了 EDIT2,以解决解析字符串的最后一个字符时的空白问题。
【解决方案2】:

使用此代码。

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;
    }
}

【讨论】:

    【解决方案3】:

    有很多方法可以解决您的问题。

    您可以使用StringBuilder 以OO 方式进行操作:

    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();
    }
    

    您也可以使用String 代替StringBuilder,只需使用+ 运算符而不是.append() 方法。

    或者您可以通过使用 Java 8 功能以更“现代”的方式来实现 - 在我看来这很有趣,但不是最好的方式 - 例如像这样:

    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
    }
    

    试试对你有用的东西。

    【讨论】:

      猜你喜欢
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-21
      • 1970-01-01
      相关资源
      最近更新 更多