【问题标题】:separate a string with spaces [closed]用空格分隔字符串[关闭]
【发布时间】:2016-08-05 13:43:51
【问题描述】:

如何使用 for 循环将用户输入的单词与空格分开。

Scanner scan = new Scanner(System.in);

  int i;

  System.out.print("Enter a word > ");
  String word = scan.next();

  for (i = 0; i < word.length(); i++) {
     System.out.print(word.charAt(i));
  }

【问题讨论】:

  • 你可以使用System.out.print(word.charAt(i) + " ");
  • 你得到的错误是什么?什么不工作?
  • 我没有收到错误消息,它只是不断打印单词,字母之间没有空格。

标签: java string for-loop char


【解决方案1】:
for(int i = 0; i < word.length(); i++){
    System.out.print(word.charAt(i) + " ");
}//end of for loop

此代码将生成一个字符串,例如“HelloWorld!”显示为: “你好!”

【讨论】:

    【解决方案2】:

    简单地说:你在打印你打印的单词后放一个空格:

    for (i = 0; i < word.length(); i++) {
       System.out.print(word.charAt(i));
    }
    System.out.print(" ");
    

    或者,您可以将整个单词打印为一个:

    System.out.print(word + " ");
    

    如果你想在每个字母之间放一个空格:

    for (i = 0; i < word.length(); i++) {
       System.out.print(word.charAt(i) + " ");
    }
    

    【讨论】:

    • 太棒了!我就知道会这么简单,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    • 2016-07-05
    相关资源
    最近更新 更多