Bash字符串处理(与Java对照) - 20_查找子串的位置
Bash字符串处理(与Java对照) -
20.查找子串的位置
In Java
String.indexOf
int indexOf(String str)
返回第一次出现的指定子字符串在此字符串中的索引。
int indexOf(String str, int fromIndex)
从指定的索引处开始,返回第一次出现的指定子字符串在此字符串
中的索引。
int lastIndexOf(String str)
返回在此字符串中最右边出现的指定子字符串的索引。
int lastIndexOf(String str, int fromIndex)
从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的
指定子字符串的索引。
StringUtils.indexOf & StringUtils.lastIndexOf static int indexOf(String str, String searchStr)
Finds the first index within a String, handling null. static int indexOf(String str, String searchStr, int startPos)
Finds the first index within a String, handling null. static int indexOfAny(String str, String[] searchStrs)
Find the first index of any of a set of potential substrings.
static int indexOfIgnoreCase(String str, String searchStr)
Case in-sensitive find of the first index within a String. static int indexOfIgnoreCase(String str, String searchStr, int startPos)
Case in-sensitive find of the first index within a String from the specified position.
static int lastIndexOf(String str, String searchStr)
Finds the last index within a String, handling null. static int lastIndexOf(String str, String searchStr, int startPos)
Finds the first index within a String, handling null.
static int lastIndexOfAny(String str, String[] searchStrs)
Find the latest index of any of a set of potential substrings.
static int lastIndexOfIgnoreCase(String str, String searchStr)
Case in-sensitive find of the last index within a String. static int lastIndexOfIgnoreCase(String str, String searchStr, int startPos)
Case in-sensitive find of the last index within a String from the specified position.
static int lastOrdinalIndexOf(String str, String searchStr, int ordinal)
Finds the n-th last index within a String, handling null.
static int ordinalIndexOf(String str, String searchStr, int ordinal)
Finds the n-th index within a String, handling null.
In Bash
使用遍历字符串的
来查找子串的位置
函数:strstr
如果找到,打印位置,从0开始计数,退出码为0;否则,打印-1,退出码为1
strstr(){
declare -i i n2=${#2} n1=${#1}-n2
#echo $i $n1 $n2
for ((i=0; i