【问题标题】:How does a null character (\u0000) end up in a string?空字符 (\u0000) 如何以字符串结尾?
【发布时间】:2016-08-14 14:28:00
【问题描述】:

我有一个类,其中有一个方法可以在字符串中包含 NUL 字符的情况下终止程序。具体的表达方式是这样的:

stringVar.indexOf('\u0000') < 0

这个字符串是通过 Scanner 从用户那里读取的,我真的很想知道一个 NUL 字符是如何通过用户的输入最终出现在字符串中的。

编辑:扫描仪读取代码如下:

Scanner scannerVar = new Scanner(System.in);
stringVar = scannerVar.next();

【问题讨论】:

  • 请使用Scanner提供代码
  • 我认为不会。方法正常吗?
  • @Codebender 我试图让它执行该方法,即通过用户输入在字符串中添加一个 NUL 字符,但我做不到。但是应该是有可能的,否则为什么类的创建者会添加这样的方法?
  • @Haggra 有一个关于字符串中的空字符的讨论。请看:stackoverflow.com/q/318775/2293534

标签: java string user-input nul


【解决方案1】:

public int indexOf(int ch):

返回此字符串中第一次出现指定字符的索引,如果没有出现,则返回 -1。

您可以使用扫描仪获得空白输入。链接在这里:https://stackoverflow.com/a/17504384/2293534

import java.io.*;

public class Test {

   public static void main(String args[]) {
      String Str = new String("Welcome to Tutorialspoint.com");
      String SubStr1 = new String("Tutorials");
      String SubStr2 = new String("Sutorials");

      System.out.print("Found Index :" );
      System.out.println( Str.indexOf( SubStr1, 15 ));
      System.out.print("Found Index :" );
      System.out.println(Str.indexOf( SubStr2 ));
   }
}

这会产生以下结果:

找到索引:-1

找到的索引:-1

资源链接:

Java - String indexOf() Method

【讨论】:

    猜你喜欢
    • 2016-05-23
    • 2011-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 2013-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多