递归是会更秀strtok

嵌入式Linux

共 4665字,需浏览 10分钟

 · 2022-06-28

前几天发的字符串反转题目,后面有一个新同学用了递归的方法来实现,看了下,真的是很秀。

之前字符串反转的题目

代码如下

#include "stdio.h"
#include "string.h"
char input[] = {"the sky is blue cris 1212321 apple"};

void reverse(char *s,char *delim) 
    char* temp = strtok(s,delim);
    if(temp != NULL) {
        reverse(NULL,delim);
        printf("%s ",temp); 
    }
}


int main() 
 printf("%s\n",input); 
 reverse(input," ");
 return 0;
}

strtok是一个字符串分割函数,但是这个函数估计很多人还不明白他的用法。

strtok函数解释

char *strtok(char s[], const char *delim)

把输入的字符串s分解成为一组字符串。

delim 为分割字符串,注意这里是字符串。

首次调用时,s指向要分解的字符串,之后再次调用要把s设成NULL

例如:

#include "stdio.h"
#include "string.h"
char input[] = {"the sky is blue cris 1212321 apple"};

int main() {
 char *temp = NULL
 printf("%s\n",input); 
 temp = strtok(input," ");
 printf("input=%s,temp=%s\n", input, temp);
 temp = strtok(NULL," ");
 printf("input=%s,temp=%s\n", input, temp);
 return 0;
}

头文件

#include<string.h>

使用详细说明

  • 开始

strtok 找到需要分割的字符串delim后,会把这个delim设置成\0 ,这从上面的实例也可以看出来,分割之后,我们再用printf输出会在第一个分割字符串位置停止输出。

  • 结束

当字符串查找到末尾时,函数会返回NULL,所以我们可以用NULL来判断函数执行是否结束。

  • 注意

用这个函数处理之后会破坏原来字符串中的内容,第一次分割之后,原字符串s是分割完成之后的第一个字符串。

strtok函数源码

char *
strtok_apple(
 register char *s,
 register const char *delim)

{
 register char *spanp;
 register int c, sc;
 char *tok;
 static char *last;


 if (s == NULL && (s = last) == NULL)
  return (NULL);

 /*
  * Skip (span) leading delimiters (s += strspn(s, delim), sort of).
  */

cont:
 c = *s++;
 for (spanp = (char *)delim; (sc = *spanp++) != 0;) {
  if (c == sc)
   goto cont;
 }

 if (c == 0) {  /* no non-delimiter characters */
  last = NULL;
  return (NULL);
 }
 tok = s - 1;

 /*
  * Scan token (scan for delimiters: s += strcspn(s, delim), sort of).
  * Note that delim must have one NUL; we stop if we see that, too.
  */

 for (;;) {
  c = *s++;
  spanp = (char *)delim;
  do {
   if ((sc = *spanp++) == c) {
    if (c == 0)
     s = NULL;
    else
     s[-1] = 0;
    last = s;
    return (tok);
   }
  } while (sc != 0);
 }
 /* NOTREACHED */
}

解释下上面的代码

#include "stdio.h"
#include "string.h"
char input[] = {"the sky is blue cris 1212321 apple"};

void reverse(char *s,char *delim) 
    char* temp = strtok(s,delim);
    if(temp != NULL) {
        reverse(NULL,delim);
        printf("%s ",temp);//第一次调用的时候会最后输出,最后一次调用不等于空的时候最先输出 
    }
}


int main() 
 printf("%s\n",input); 
 reverse(input," ");
 return 0;
}

如果递归理解不是很明白,可以用for来输出看看

#include "stdio.h"
#include "string.h"
char input[] = {"the sky is blue cris 1212321 apple"};

int main() {
 char * output[1024]; 
 int len = 0
 
 printf("%s\n",input);
 
 char* temp = strtok(input," "); 
 
 for (len=0;temp!=NULL;temp = strtok(NULL," "),++len) {
  output[len] = temp;
 }
 
 for(;len--;) {
  printf("%s ", output[len]);
 }
 return 0;
}


浏览 29
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报