一、原题
链接:Training on Retrieve The N-th String Term | Codewars
This Kata requires you to retrieve the n-th string from a character array, where a null character separates each string, and a double null character terminates the character array. The Kata abides by the following rules:
|
二、解题
1、分析
1)不要申请动态,否则返回的内存空间与要求不一致
该函数必须返回一个指向缓冲区的指针,该缓冲区基于索引作为参数传递 |
2)如果n小于零或大于或等于可用字符串,则函数必须返回 NULL
3)字符串通过‘\0’分割成几个部分,字符串以‘\0\0’为终止
Array : "hello\0world\0\0" | Output: pointer to the string "hello" |
Array : "well\0done\0\0" | Output: pointer to the string "done" |
Array : "the\0brown\0fox\0jumps\0over\0the\0lazy\0dog\0\0" | Output: pointer to the string "dog" |
可发现‘\0’将字符串进行分割,从零开始编号
2、思路
1)新建指针*p用于存储返回字符串的起始地址;
const char *p;
2) item用于记录读了几个‘\0’;读到'\0',则item++;
int item=0;
if(*input=='\0'){
item++;
}
3)通过 while(*input || *(input+1) ) 遍历字符串【跟前辈请教的,真是大开眼界】
直接return p关键在于原字符串自带‘\0’
三、Myway
#include <stdlib.h>
#include<stdio.h>
/*
Return a pointer to the buffer.
*/
const char *extract_string(const char *input, const int n)
{ //printf("%s\n",input);
if(n<0) return NULL;
int item=0;
const char *p;
while(*input || *(input+1) ){
//printf("%c \n",*p);
if(*input=='\0'){
item++;
}
else{
if(n==0){
p=input;
return p;
}
else if(n==item){
p=input;
return p;
}
}
input++;
}
return NULL;
}