Pointers on C——9 Strings, Characters, and Bytes.7

9.6 Advanced String Searching

高级字符串查找


The next group of functions simplify the location and extraction of individual substrings from a string.

接下来的一组函数简化了从一个字符串中查找和抽取一个子串的过程。


9.6.1 Finding String Prefixes

The strspn and strcspn functions count characters at the beginning of a string. Their prototypes are shown :

strspn 和strcspn 函数用于在字符串的起始位置对字符计数。它们的原型如下所示:


size_t strspn( char const *str, char const *group );

size_t strcspn( char const *str, char const *group );


The group string specifies one or more characters. strspn returns the number of characters at the beginning of str that match any of these characters. For example, if group contained the whitespace characters space, tab, and so forth, this function would return the number of whitespace characters found at the beginning of str. The next character of str would be the first non‐whitespace character.

group 字符串指定一个或多个字符。strspn 返回str起始部分匹配group 中任意字符的字符数。例如,如果group 包含了空格、制表符等空白字符,那么这个函数将返回str起始部分空白字符的数目。str 的下一个字符就是它的第1 个非空白字符。


Consider this example:

考虑下面这个例子:


int len1, len2;

char buffer[] = "25,142,330,Smith,J,239-4123";

len1 = strspn( buffer, "0123456789" );

len2 = strspn( buffer, ",0123456789" );


Of course, the buffer would not normally be initialized in this manner; it would contain data read in at run time. But with this value in the buffer, the variable len1 would be set to two, and the variable len2 would be set to 11. The following code will compute a pointer to the first non‐whitespace character in a string.

当然, buffer 缓冲区在正常情况下是不会用这个方法进行初始化的。它将会包含在运行时读取的数据。但是在buffer 中有了这个值之后,变量len1 将被设置为2 ,变量len2将被设置为11。 下面的代码将计算一个指向于符串中第1 个非空白字符的指针。


ptr = buffer + strspn( buffer, " \n\r\f\t\v" );


strcspn works similarly except that only characters that are not in group are counted. The c in the name strcspn comes from the notion that the character group is complemented, that is, exchanged for all of the characters it did not originally contain. If you used the string ʺ \n\r\f\t\vʺ for the group argument, this function would return the number of non‐whitespace characters found at the beginning of the first argument.

strcspn 函数和strspn 函数正好相反,它对str 字符串起始部分中不与group 中任何字符匹配的字符进行计数。strcspn 这个名字中字母c 来源于对一组字符求补这个概念,也就是把这些字符换成原先并不存在的字符。如果你使用\n\r\f\t\v作为group 参数,这个函数将返回第1 个参数字符串起始部分所有非空白字符的值。


上一章 Pointers on C——9  Strings, Characters, and Bytes.6

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值