【问题标题】:null. empty, white space string in java空值。 java中的空白字符串
【发布时间】:2017-10-01 13:11:42
【问题描述】:

在以下代码中:

import java.util.*; 
 public class test{     
     public static void main(String[] args){             
         System.out.println("".length());     
     }
 }

输出为 0。

但在以下代码中:

import java.util.*;
public class test{
    public static void main(String[] args){
        System.out.println("Please enter a string: ");
        Scanner stdin = new Scanner(System.in);
        String st = stdin.next();
        System.out.println(st.length());
        System.out.println(st.equals(""));
    }
}

当我输入 "" 或空字符串时,输出是:

2
false

我将std.next() 更改为std.nextLine(),但输出相同。

当我将System.out.println(st.equals("")); 更改为System.out.println(st.equals(" ")); 我输入“”或空格输出是:

1
false

这是为什么呢?

【问题讨论】:

  • 考虑newline(输入)。试试st.trim().length() 和st.trim().equals("")。
  • 你把java字符串和输入字符串搞混了

标签: java string null whitespace


【解决方案1】:

输入 "" 是两个字符,这就是为什么你得到长度 2 和 "" 是不等于一个空字符串。至于第二种情况,当您输入 " " 时,您的长度为 1,因为 String::next() 只能读取用户输入直到空格。它无法读取由空格分隔的两个单词,并且 不等于 是一个空字符串。总而言之,使用String::next() 时不能输入空字符串,甚至不能输入用空格填充的字符串。为此,您需要使用 String::nextLine()。

在读取用户输入时,我们不会将空字符串表示为""。 空字符串是长度为零的字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 2013-11-04
    • 2018-02-16
    相关资源
    最近更新 更多