搞一个公司网站得多少钱,安卓app制作平台,wordpress源码解读,中文wordpress企业主题在给定的字符串中查找字符或字符串是比较常见的操作。字符串查找分为两种形式#xff1a;一种是在字符串中获取匹配字符#xff08;串#xff09;的索引值#xff0c;另一种是在字符串中获取指定索引位置的字符。
根据字符查找
String 类的 indexOf() 方法和 lastlndexOf…在给定的字符串中查找字符或字符串是比较常见的操作。字符串查找分为两种形式一种是在字符串中获取匹配字符串的索引值另一种是在字符串中获取指定索引位置的字符。
根据字符查找
String 类的 indexOf() 方法和 lastlndexOf() 方法用于在字符串中获取匹配字符串的索引值。
1. indexOf() 方法
indexOf() 方法用于返回字符串在指定字符串中首次出现的索引位置如果能找到则返回索引值否则返回 -1。该方法主要有两种重载形式
str.indexOf(value)str.indexOf(value,int fromIndex)
其中str 表示指定字符串
value 表示待查找的字符串
fromIndex 表示查找时的起始索引如果不指定 fromIndex则默认从指定字符串中的开始位置即 fromIndex 默认为 0开始查找。
例如下列代码在字符串“Hello Java”中查找字母 v 的索引位置。
String s Hello Java;
int size s.indexOf(v); // size的结果为8上述代码执行后 size 的结果为 8它的查找过程如图 1 所示。 例 1 编写一个简单的 Java 程序演示 indexOf() 方法查找字符串的用法并输出结果。代码如下
public static void main(String[] args) {String words today,monday,sunday;System.out.println(原始字符串是words);System.out.println(indexOf(\day\)结果words.indexOf(day));System.out.println(indexOf(\day\,5)结果words.indexOf(day,5));System.out.println(indexOf(\o\)结果words.indexOf(o));System.out.println(indexOf(\o\,6)结果words.indexOf(o,6));
}运行后的输出结果如下
原始字符串是today,monday,sunday
indexOf(day)结果2
indexOf(day,5)结果9
indexOf(o)结果1
indexOf(o,6)结果72. lastlndexOf() 方法
lastIndexOf() 方法用于返回字符串在指定字符串中最后一次出现的索引位置如果能找到则返回索引值否则返回 -1。该方法也有两种重载形式
str.lastIndexOf(value)str.lastlndexOf(value, int fromIndex)
注意lastIndexOf() 方法的查找策略是从右往左查找如果不指定起始索引则默认从字符串的末尾开始查找。 例 2 编写一个简单的 Java 程序演示 lastIndexOf() 方法查找字符串的用法并输出结果。代码如下
public static void main(String[] args) {String wordstoday,monday,Sunday;System.out.println(原始字符串是words);System.out.println(lastIndexOf(\day\)结果words.lastIndexOf(day));System.out.println(lastIndexOf(\day\,5)结果words.lastIndexOf(day,5));System.out.println(lastIndexOf(\o\)结果words.lastIndexOf(o));System.out.println(lastlndexOf(\o\,6)结果words.lastIndexOf(o,6));
}运行后的输出结果如下
原始字符串是today,monday,Sunday
lastIndexOf(day)结果16
lastIndexOf(day,5)结果2
lastIndexOf(o)结果7
lastlndexOf(o,6)结果1根据索引查找
String 类的 charAt() 方法可以在字符串内根据指定的索引查找字符该方法的语法形式如下 字符串名.charAt(索引值) 提示字符串本质上是字符数组因此它也有索引索引从零开始。
charAt() 方法的使用示例如下
String words today,monday,sunday;
System.out.println(words.charAt(0)); // 结果t
System.out.println(words.charAt(1)); // 结果o
System.out.println(words.charAt(8)); // 结果n