本地建站软件,wordpress二维码动态图片大小,wordpress点击阅读全文,网站建设属于现代服务吗目录
1.查找字符
#xff08;1#xff09;以索引查找字符 #xff08;2#xff09;以字符查找索引
2.查找字符串 在给定的字符串中查找需要的字符或字符串是常见的操作#xff0c;以下是String类中常用的查找方法。
1.查找字符
查找字符分为两种情况#xff1a;一种…目录
1.查找字符
1以索引查找字符 2以字符查找索引
2.查找字符串 在给定的字符串中查找需要的字符或字符串是常见的操作以下是String类中常用的查找方法。
1.查找字符
查找字符分为两种情况一种是根据索引查找该索引处的字符另一种是根据给定的字符查找该字符的索引
1以索引查找字符
方法 char charAt(int index) 该方法返回 index 位置上的字符若 index 为负数或是越界则抛出StringIndexOutOfBoundsException 异常
public class Test {public static void main(String[] args) {String str abcdefg;char ch str.charAt(2);System.out.println(ch);//输出c}
} 2以字符查找索引
由于字符在字符串中可能出现多次因此查找的方式不同返回的索引也不相同可以从前向后查找、从后向前查找或是从指定位置开始查找
方法 int indexOf(int ch) 从0索引开始找ch返回ch第一次出现的位置没有则返回 -1
public class Test {public static void main(String[] args) {String str abcdefgaaa;int index1 str.indexOf(a);int index2 str.indexOf(m);System.out.println(index1);//输出0System.out.println(index2);//字符串中无字符m找不到返回-1.因此输出-1}
}方法 int lastIndexOf(int ch) public class Test {public static void main(String[] args) {String str abcdefgaaa;int index str.lastIndexOf(a);System.out.println(index);//输出9}
}
方法 int indexOf(int ch, int formIndex) 从 fromIndex 位置开始找ch第一次出现的位置没有则返回 -1
public class Test {public static void main(String[] args) {String str abcdefgaaa;int index str.indexOf(a,3);//从3索引位置开始找aSystem.out.println(index);//输出7}
}
方法 int lastIndexOf(int ch, int fromIndex) 从 fromIndex 位置开始向前找ch第一次出现的位置没有则返回 -1
public class Test {public static void main(String[] args) {String str abcdefgaaa;int index str.lastIndexOf(a,8);//从8索引位置开始向前查找aSystem.out.println(index);//输出8}
}
2.查找字符串
由于字符串在指定的字符串中也可能出现多次因此也可以从前向后查找、从后向前查找或是从指定位置开始查找。
方法 int indexOf(String str) 从0索引位置开始查找字符串str返回 str 第一次出现的位置没有则返回 -1
public class Test {public static void main(String[] args) {String str aaabbbcccdedfg;String s abc;int index str.indexOf(s);//字符串str中不包含abc返回-1System.out.println(index);//输出-1}
}
方法 int indexOf(String str, int fromIndex) 从fromIndex位置开始查找 str返回 str 第一次出现的位置没有则返回 -1
public class Test {public static void main(String[] args) {String str aaabbbcccdedfg;String s bbc;int index str.indexOf(s,3);System.out.println(index);//输出4}
}
方法 int lastIndexOf(String str) 从后向前找返回 str 第一次出现的位置没有则返回-1
public class Test {public static void main(String[] args) {String str abcabcabc;String s abc;int index str.lastIndexOf(s);System.out.println(index);//输出6}
} 方法 int lastIndexOf(String str, int fromIndex) 从 fromIndex 位置开始向前查找 str返回 str 第一次出现的位置没有则返回 -1
public class Test {public static void main(String[] args) {String str abcabcabc;String s abc;int index str.lastIndexOf(s,5);//从5索引位置开始向前查找sSystem.out.println(index);//输出3}
}