判断一个长的字符串中,是否包含一个小的字符串
需求:一个长的字符串为:aberdandyertfd。
一个短的字符串为:andy 那么就是包含,否则不包含
运用到的技术点:
1.for循环
2.if判断
3.String.leng 获取字符串长度
4.String.charAt() 获取字符串对应索引的 数据转换成 字符类型char。
例如 String name = "abc"; char a = name.char(0); 输出: a = 'a';
5.String.equals() 判断两个字符串中的内容是否一致,一致就返回 true,反之 false
6.方法
1.刚入门的做法
i = 3时的效果
public class Demo {
public static void main(String[] args) {
String wordLong = "aberdandyertfd";
String wordShort = "yertfd";
System.out.println(judgeInclude(wordLong, wordShort));
}
public static boolean judgeInclude(String wordLong, String wordShort) {
String a = "";
String b = "";
for (int i = 0; i < wordLong.length(); i++) {
a += wordLong.charAt(i);
System.out.println("a1 = " + a);
if (i >= wordShort.length()) {
System.out.println("a.length() = " + (a.length() - wordShort.length()));
System.out.println("a.length() = " + a.length());
for (int j = a.length() - wordShort.length(); j < a.length(); j++) {
b += a.charAt(j);
System.out.println("b = " + b);
if (wordShort.equals(b)) {
return true;
}
}
b = "";
}
}
return false;
}
}
i = 4 时的效果
public static boolean judgeInclude(String wordLong, String wordShort) {
String a = "";
String b = "";
for (int i = 0; i < wordLong.length(); i++) {
a += wordLong.charAt(i);
System.out.println("a1 = " + a);
if (i >= wordShort.length()) {
System.out.println("a.length() = " + (a.length() - wordShort.length()));
System.out.println("a.length() = " + a.length());
for (int j = a.length() - wordShort.length(); j < a.length(); j++) {
b += a.charAt(j);
System.out.println("b = " + b);
if (wordShort.equals(b)) {
return true;
}
}
b = "";
}
}
return false;
}
}
2.采用jdk String的substring方法。
public String substring(int beginIndex, int endIndex)
beginIndex -- 起始索引(包括), 索引从 0 开始。
endIndex -- 结束索引(不包括)
public class Demo {
public static void main(String[] args) {
String wordLong = "aberdandyertfd";
String wordShort = "ber";
System.out.println(judgeInclude(wordLong, wordShort));
}
public static boolean judgeInclude(String wordLong, String wordShort) {
for (int i = 0; i < wordLong.length() - wordShort.length(); i++) {
if (wordLong.substring(i, i + wordShort.length()).equals(wordShort)) {
return true;
}
}
return false;
}
}
3.采用 正则表达式方法。
public class Demo {
public static void main(String[] args) {
String wordLong = "aberdandyertfd";
String wordShort = "ye";
System.out.println(judgeInclude(wordLong, wordShort));
}
public static boolean judgeInclude(String wordLong, String wordShort) {
String target = "(.*" + wordShort + ".*)*";
if (wordLong.matches(target)) {
return true;
}
return false;
}
}
4.采用 contains() 方法。
public boolean contains(CharSequence chars)
contains() 方法用于判断字符串中是否包含指定的字符或字符串。
public class Demo {
public static void main(String[] args) {
String wordLong = "aberdandyertfd";
String wordShort = "ye";
System.out.println(wordLong.contains(wordShort));
}
}