java 输入两个字符串,然后检测第二个字符串是否包含于第一个串中?要求第一个字符串可以是带空格的句子

编写程序,提示从键盘输入两个字符串,然后检测第二个字符串是否包含于第一个串中?例如,字符串“Lambda expressions let you express instances of single-method classes more compactly.”和“express”,其中“express”包含于第一个字符串内。我编的不行 。

import java.util.Scanner;
import java.io.*;
import java.util.*;
public class demo {
public static void main(String[] args) {
Scanner sin=new Scanner(System.in);
String str1=sin.next();
String str2=sin.next();
if(str1.contains(str2))
System.out.println("Yes");
else
System.out.println("No");
}

你获取控制台输入的方法错了,应该用nextLine():获取下一行输入的数据

import java.io.IOException;
import java.util.Scanner;

public class Test {
public static void main(String[] args) throws IOException {
Scanner sin = new Scanner(System.in);
String str1 = sin.nextLine();
String str2 = sin.nextLine();
if (str1.contains(str2))
System.out.println("Yes");
else
System.out.println("No");
}
}

例子:


对于next()方法:
next()方法会自动将其去掉,只有在输入有效字符之后,next()方法才将其后输入的空格键、Tab键或Enter键等视为分隔符或结束符
例如:你输入:is-myname,然后输入空格,代表一次输入完毕,在输入is时完成第二次输入,这是将大约yes

温馨提示:内容为网友见解,仅供参考
第1个回答  2017-05-27

Java程序:

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str1, str2;

System.out.println("字符串1:");
str1 = scan.nextLine();
System.out.println("字符串2:");
str2 = scan.nextLine();

if(str1.indexOf(str2) >= 0) {
System.out.println("字符串 \"" + str2 + "\" 在字符串 \"" + str1 + "\" 中存在");
}
else {
System.out.println("字符串 \"" + str2 + "\" 在字符串 \"" + str1 + "\" 中不存在");
}
}
}


运行测试:

字符串1:
Lambda expressions let you express instances of single-method classes more compactly.
字符串2:
express
字符串 "express" 在字符串 "Lambda expressions let you express instances of single-method classes more compactly." 中存在

本回答被提问者采纳
第2个回答  2017-05-27
可以使用indexOf

~
~
~
相似回答