Bash字符串处理(与Java对照) - 15.计算子串出现的次数
In Java
StringUtils.countMatches
org.apache.commons.lang.StringUtils countMatches方法 写道
public static int countMatches(String str, String sub)
Counts how many times the substring appears in the larger String.
A null or empty ("") String input returns 0.
StringUtils.countMatches(null, *) = 0
StringUtils.countMatches("", *) = 0
StringUtils.countMatches("abba", null) = 0
StringUtils.countMatches("abba", "") = 0
StringUtils.countMatches("abba", "a") = 2
StringUtils.countMatches("abba", "ab") = 1
StringUtils.countMatches("abba", "xxx") = 0
Parameters:
str - the String to check, may be null
sub - the substring to count, may be null
Returns:
the number of occurrences, 0 if either String is null
Counts how many times the substring appears in the larger String.
A null or empty ("") String input returns 0.
StringUtils.countMatches(null, *) = 0
StringUtils.countMatches("", *) = 0
StringUtils.countMatches("abba", null) = 0
StringUtils.countMatches("abba", "") = 0
StringUtils.countMatches("abba", "a") = 2
StringUtils.countMatches("abba", "ab") = 1
StringUtils.countMatches("abba", "xxx") = 0
Parameters:
str - the String to check, may be null
sub - the substring to count, may be null
Returns:
the number of occurrences, 0 if either String is null
countMatches的实现代码
(摘自 StringUtils)
public static int countMatches(String str, String sub) { if (isEmpty(str) || isEmpty(sub)) { return 0; } int count = 0; int idx = 0; while ((idx = str.indexOf(sub, idx)) != INDEX_NOT_FOUND) { count++; idx += sub.length(); } return count; } public static final int INDEX_NOT_FOUND = -1; public static boolean isEmpty(String str) { return str == null || str.length() == 0; }
In Bash
子串出现的次数
格式:grep -o "$SUB" <<<"$STR" | wc -l
错误:grep -c -o "$SUB" <<<"$STR" 注:开始以为这个可以,经过检验之后不行,因为-c参数只会打印匹配的的行数。
man grep 写道
-o, --only-matching
Show only the part of a matching line that matches PATTERN.
-c, --count
Suppress normal output; instead print a count of matching lines for each input file. With the -v,
--invert-match option (see below), count non-matching lines.
Show only the part of a matching line that matches PATTERN.
-c, --count
Suppress normal output; instead print a count of matching lines for each input file. With the -v,
--invert-match option (see below), count non-matching lines.
[root@jfht ~]# x="This is a test"
[root@jfht ~]# grep -o "t" <<<"$x" | wc -l
2
[root@jfht ~]# grep -o "T" <<<"$x" | wc -l
1
[root@jfht ~]# grep -o "[tT]" <<<"$x" | wc -l
3
[root@jfht ~]# grep -o "t|T" <<<"$x" | wc -l
0
[root@jfht ~]# grep -o "t\|T" <<<"$x" | wc -l
3
字符出现的次数
格式:TMP=${STR//[^cC]}; ${#TMP}
意思是说将STR字符串中所有不是c和C的字符删除掉,保存到TMP中,那么得到TMP的长度就是c或C出现的次数
[root@jfht ~]# x="This is a test"
[root@jfht ~]# y=${x//[^tT]}
[root@jfht ~]# echo $y
Ttt
[root@jfht ~]# echo ${#y}
3
本文链接:http://codingstandards.iteye.com/blog/1182146 (转载请注明出处)
返回目录:Java程序员的Bash实用指南系列之字符串处理(目录)