2012年(158)
分类: C/C++
2012-11-23 16:41:16
char* strchr( const char* str, int chr );
在str中查找第一次出现的chr,没找到则返回0
char* strrchr( const char* str, int chr );
在str中查找最后一次出现的chr,没找到则返回0
char* strstr( const char* str, const char* substr
);
在str中查找第一次出现的substr,没找到则返回0
size_t strspn( const char* str, const char* chrset );
在str中查找
只包含在chrset中的字符 的最开始的最长字符数目
strspn( "cabbage", "abc" ) == 5;
strspn(
"cabbage", "dc" ) == 1;
strspn( "cabbage", "d" ) == 0;
strspn( str,
"abceg" ) == 7;
char* strspnp( const char* str, const char* chrset
);
和strspn功能一样,只是返回指针
const char* str = "cabbage"
strspnp( str, "abc" )
== str+5;
strspnp( str, "dc" ) == str+1;
strspnp( str, "d" ) ==
str+0;
strspnp( str, "abceg" ) == 0; // 和strspn不一样
size_t strcspn( const char* str, const char* chrset
);
在str中查找第一次出现在chrset中的字符位置,没找到则返回str结尾的'\0'的位置
strcspn( "xyzbxz", "abc"
) = 3
strcspn( "xyzbxz", "xyz" ) = 0
strcspn( "xyzbxz", "no match" ) =
6
strcspn( "xyzbxz", "" ) = 6
strcspn( "", "abc" ) = 0
strcspn( "", ""
) = 0
char* strpbrk( const char* str, const char* chrset
);
和strcspn功能一样,只是返回指针
strpbrk( "xyzbxz", "abc" ) = "xyzbxz"+3
strpbrk(
"xyzbxz", "xyz" ) = "xyzbxz"+0
strpbrk( "xyzbxz", "no match" ) = 0 //
和strcspn不一样
strpbrk( "xyzbxz", "" ) = 0 // 和strcspn不一样
strpbrk( "", "abc"
) = 0 // 和strcspn不一样
strpbrk( "", "" ) = 0 // 和strcspn不一样
------------------------
假如想将 "123@456@789" 分割成 "123" "456" "789" 当用 strchr
假如想将 "123@#456@#789"
分割成 "123" "456" "789" 当用 strstr
假如想将 "123@456#789@#0" 分割成 "123" "456" "789"
"" "0" 当用 strcspn
假如想将 "123@456#789@#0" 分割成 "123" "456" "789" "0" 当用
strcspn/strspn
代码如下:(未曾测试过)
#include
#include
#include
void split001( const char* str, const char chr )
{
const char* p1 =
str;
for( const char* p2; (p2=strchr(p1,chr))!=0; p1=p2+1 )
{
printf( "\"%.*s\"\n", p2-p1, p1 );
}
printf(
"\"%s\"\n", p1 );
}
void split002( const char* str, const char* substr
)
{
assert( *substr );
const size_t substrlen =
strlen(substr);
const char* p1 = str;
for( const char* p2;
(p2=strstr(p1,substr))!=0; p1=p2+substrlen )
{
printf(
"\"%.*s\"\n", p2-p1, p1 );
}
printf( "\"%s\"\n", p1
);
}
void split003( const char* str, const char* substr )
{
assert( *substr );
const char* p1 = str;
for( const char* p2;
p2=p1+strcspn(p1,substr), *p2; p1=p2+1 )
{
printf(
"\"%.*s\"\n", p2-p1, p1 );
}
printf( "\"%s\"\n", p1
);
}
void split004( const char* str, const char* substr )
{
assert( *substr );
const char* p1 = str;
for( const char* p2;
p2=p1+strcspn(p1,substr), *p2; p1=p2+strspn(p2,substr) )
{
printf( "\"%.*s\"\n", p2-p1, p1 );
}
printf( "\"%s\"\n", p1
);
}
int main( void )
{
split001( "123@456@789", '@' );
printf(
"---\n" );
split002( "123@#456@#789", "@#" );
printf( "---\n"
);
split003( "123@456#789@#0", "@#" );
printf( "---\n" );
split004( "123@456#789@#0", "@#" );
printf( "---\n" );
return 0;
}