【问题标题】:String contains () in Java returns false even if string is presentJava中的String contains()即使存在字符串也会返回false
【发布时间】:2018-02-01 19:37:57
【问题描述】:

我目前正在学习Java编程,正在练习String contains(),它用于检查字符串中的特定字符串是否存在。但是在给定的代码中,即使字符串存在, contains() 也会返回 false。

import java.util.*;
class StringPractice1{
public static void main(String arg[]){
    System.out.println("Enter a string:- ");
    Scanner sc1 = new Scanner(System.in);
    String s1 = sc1.next();
    System.out.println("Enter the string you want to find:- ");
    Scanner sc2 = new Scanner(System.in);
    String s2 = sc2.next();
    if(s1.contains(s2)){
        System.out.println("It contains the string '"+s2+"'.");
    }
    else{
        System.out.println("No such string exists.");
    }
}}

Output screen

【问题讨论】:

  • Scanner 上的 next() 只返回一个词,而不是整行。另外,不要对每个输入都使用新的Scanner。行为可能不是您所期望的。
  • 我的猜测是扫描仪输入的行分隔符有问题。
  • else 块之后添加以下内容,您会看到会发生什么:System.out.printf("s1:"+s1+"; s2:"+s2+";");
  • @ajb 我认为你是对的,这是 next() 的问题,因为它对句子的起始词返回 true。感谢您的帮助。

标签: java string contains


【解决方案1】:
String s1 = sc1.next();

在你的情况下只会使用一个词,即I,因为出现了空格。

但是,如果您使用sc1.nextLine();,则会使用整个句子,即“我是男孩”。从而解决您的问题。

【讨论】:

  • 谢谢,这正是我想要的。
猜你喜欢
  • 1970-01-01
  • 2020-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-26
相关资源
最近更新 更多