Bash字符串处理(与Java对照) - 8.计算字符串长度
In Java
取字符数量
一个汉字算1个字符。
int len = s.length();
Returns the length of this string. The length is equal to the number of Unicode code units in the string.
Specified by:
length in interface CharSequence
Returns:
the length of the sequence of characters represented by this object.
取字节数量
一个汉字算几个字节,取决于编码方式。
int numOfBytes = s.getBytes().length;
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.
byte[] getBytes(Charset charset)
Encodes this String into a sequence of bytes using the given charset, storing the result into a new byte array.
byte[] getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.
In Bash
取变量STR的长度(推荐方式)
格式:${#STR}
[root@jfht ~]# STR="Hello World"
[root@jfht ~]# echo ${#STR}
11
使用expr length命令取字符串长度
用expr命令,也可以取到字符串长度,但都没有上面的高效,因为上面的方式是Bash内置的方式,而expr命令是外部命令。
格式:expr length $STR
length of STRING
使用expr match命令取字符串长度
格式1:expr "$STR" : ".*"
格式2:expr match "$STR" ".*"
anchored pattern match of REGEXP in STRING
match STRING REGEXP
same as STRING : REGEXP
[root@jfht ~]# STR="Hello World"
[root@jfht ~]# expr length $STR
expr: 语法错误
因为STR中包含空白,造成了问题,要加上双引号。
[root@jfht ~]# expr length "$STR"
11
[root@jfht ~]# expr "$STR" : ".*"
11
[root@jfht ~]# expr match "$STR" ".*"
11
用wc命令取字符串长度
使用wc命令也可以实现字符串长度计算。
格式1:wc -c <<<"$STR"
比实际的字节数多1,会多输出一个换行,等同于 echo "$STR" | wc -c 而不是下面这个
格式2:echo -n "$STR" | wc -c
上面是计算字节数,如果是中文的话,每个中文为2个字节(当LANG=zh_CN.GB18030)。
格式3:wc -m <<<"$STR"
比实际的字符数多1,会多输出一个换行,等同于 echo "$STR" | wc -m 而不是下面这个
格式4:echo -n "$STR" | wc -m
上面是计算字符数,与${#STR}相同,每个汉字是按1个字符计算。
print the byte counts
-m, --chars
print the character counts
[root@jfht ~]# STR=123456789
[root@jfht ~]# echo ${#STR}
9
[root@jfht ~]# wc -c <<<"$STR "
10
[root@jfht ~]# echo -n "$STR" | wc -c
9
[root@jfht ~]# wc -m <<<"$STR"
10
[root@jfht ~]# echo -n "$STR" | wc -m
9
[root@jfht ~]# STR=今年是2011年
[root@jfht ~]# echo ${#STR}
8
[root@jfht ~]# wc -c <<<"$STR"
13
[root@jfht ~]# echo -n "$STR" | wc -c
12
[root@jfht ~]# wc -m <<<"$STR"
9
[root@jfht ~]# echo -n "$STR" | wc -m
8
[root@jfht ~]# STR="Hello World"
[root@jfht ~]# echo ${#STR}
11
[root@jfht ~]# wc -c <<<"$STR"
12
[root@jfht ~]# echo -n "$STR" | wc -c
11
[root@jfht ~]# wc -m <<<"$STR"
12
[root@jfht ~]# echo -n "$STR" | wc -m
11
、
本文链接:http://codingstandards.iteye.com/blog/1173125 (转载请注明出处)
返回目录:Java程序员的Bash实用指南系列之字符串处理(目录)