可以使用String类中的indexOf方法检测一个字符串是否为另一个字符串的子串。编写自己的方法实现这一功能。编写一个程序,提示用户输入两个字符串,检测第一个字符串是否为第二个串的子串。
解决方案 »
- rational rose 7 下载地址
- java如何访问access2003数据库?(需要详细的步骤)
- 请大家解答下Graphics或Graphics2D的drawString方法是在那里实现的
- 一个关于for和whle的基础题目,高分求解
- java中的 System.exit(int status) 中的参数int status是撒意思呀~~怎么用呀?谢啦~~~
- java 生成exe出现问题
- POI 的读取excel问题。
- 请问文件thinkingInJava(II).zip.jc!用什么打开??
- 如何删调一个文件!在线等待,急!
- 请问谁知道那有classes.zip for jdk1.2 ?
- java可以读取jar里 Properties 可以写入到jar里么
- 不知道有没有影响?
import java.util.Scanner;
public class StrSimpleMatch {
public boolean Input()
{
Character[] S,P;
System.out.println("请输入主串:");
Scanner Sin = new Scanner(System.in);
String SStr=Sin.nextLine();
int SLength = SStr.length();
S = new Character[SLength+1];
for(int i=0;i<SLength;i++)
{
S[i] = new Character(SStr.charAt(i));
//System.out.println(S[i]);
}
S[SLength] = new Character(' ');
System.out.println("请输入模式串:");
Scanner Pin = new Scanner(System.in);
String PStr = Pin.nextLine();
int PLength = PStr.length();
P = new Character[PLength+1];
for(int i=0;i<PLength;i++)
{
P[i] = new Character(PStr.charAt(i));
//System.out.println(P[i]);
}
P[PLength] = new Character(' ');
int i=0,j=0;
while(i<=SLength && j<=PLength)
{
if(S[i].equals(P[j]))
{
i++;
j++;
}
else
{
if(j==PLength){System.out.println(PLength);}
else
{
i=i-j+1;
j=0;
}
}
if(j==(PLength))
{
System.out.println("字符串匹配成功:"+ "第"+(i-P.length+2)+"个开始");
return true;
}
}
return false;
}
public static void main(String[] args)
{
StrSimpleMatch ToCompare= new StrSimpleMatch();
boolean flag=ToCompare.Input();
if(flag==false)
{
System.out.println("字符串匹配不成功");
}
}
}
String s2 = "abcdefghijk"; System.out.println( s2.matches( "\\w*"+s1+"\\w*" ) );
public static void main(String[] args){
System.out.println("请输入主串:");
Scanner Sin = new Scanner(System.in);
String S1 = Sin.nextLine();
System.out.println("请输入子串:");
Scanner Sin2 = new Scanner(System.in);
String S2 = Sin2.nextLine();
int n = S1.indexOf(S2);
if(n == -1){
System.out.println("字符串匹配不成功");
}else{
System.out.printf("匹配成功,主串的第%d位开始",n);
}
}
}参考一下