【C】对于字符数组的一种分割方式,指针分割法。

1.赋值法

在C\C++语言中,字符数组经常被用到,但是,仍然有一些细节的地方是需要注意的。之前在做项目的时候,也碰到类似的问题。现在把这个知识点记录下来,方便自己查找,也方便大家交流。

       一个典型的字符数组可以定义为:

char  a[100] = "i love you so much !";

或者采用指针的形式:

char   *pcCharA = "i love you so much !";

        如果我们想把每个单词都分割出来,一个简单的方法是遍历,找到空格,然后取出来。但是,有了指针后,速度就很快了,

例如上面的例子:

我们可以让:*(pcCharA + 1) = '\0', *(pcCharA + 6) = '\0', *(pcCharA + 10) = '\0', *(pcCharA + 13) = '\0', *(pcCharA + 18) = '\0'.

        当我们想取第一个i 的时候,直接用 char *ptmp = pcCharA 即可,这是,ptmp就指向了“i”; 同理,char *ptmp = (pcCharA + 6)就指向了“you”.这样做就很方便了,少了很多循环来查找。

        这主要是因为,‘\0’是一个空置,字符数组遇到他就会终止,停止往后寻找数值。

2.以下为一种新的方法,比较好的方法

char str[] = "now $| is the time for all $| good men to come to the $| aid of their country";
char delims[] = "$|";
char *result = NULL;

result = strtok( str, delims );

while( result != NULL )
{
printf( "result is \"%s\"\n", result );
result = strtok( NULL, delims );
}

猜你喜欢

转载自blog.csdn.net/m0_37362454/article/details/81295844
今日推荐