【问题标题】:How to trim white space in StringBuffer in JAVA [duplicate]如何在JAVA中修剪StringBuffer中的空白[重复]
【发布时间】:2018-09-04 06:32:11
【问题描述】:

我试图使用 StringBuffer 中提供的预定义方法 reverse() 来反转字符串 我从用户那里获取输入,并在打印反向字符串时使用 toString() 方法来避免额外的空间

import java.util.*;

public class Small {

    public static void main(String a[])
    {
    int num;

    Scanner sc=new Scanner(System.in);

    num = sc.nextInt();

    while(num>0)
    {
       String t;

           t=sc.nextLine();

       StringBuffer sb=new StringBuffer(t);

        sb.reverse();

       System.out.println(sb.toString());

     num--;  
        }
    }
}

输入:

   2
   hello
   welcome

输出:

<Empty line>
olleh

谁能告诉我为什么这个空白空间来了,也没有得到第二个输出?

【问题讨论】:

  • 使用StringBuilder 而不是StringBuffer。你不需要同步。

标签: java string reverse tostring stringbuffer


【解决方案1】:

sc.nextInt() 不使用包含数字的行末尾的换行符。

在其后添加sc.nextLine();:

num = sc.nextInt();
sc.nextLine();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-14
    • 2021-08-15
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 2013-10-27
    相关资源
    最近更新 更多