Retrieve The N-th String Term——C语言提高题

一、原题

链接: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:

  • The function must return a pointer to the buffer passed as an argument based on the index n;
  • If n is less than zero or more than or equal to the available strings, the function must return NULL;
  • The array will always be populated with at least one string, so there's no need to worry about empty arrays.

二、解题

1、分析

1)不要申请动态,否则返回的内存空间与要求不一致

该函数必须返回一个指向缓冲区的指针,该缓冲区基于索引作为参数传递n;

2)如果n小于零或大于或等于可用字符串,则函数必须返回 NULL 

3)字符串通过‘\0’分割成几个部分,字符串以‘\0\0’为终止

Array :

"hello\0world\0\0"
n     : 0

Output:

pointer to the string "hello"

Array :

"well\0done\0\0"
n     : 1

Output:

pointer to the string "done"

Array : "the\0brown\0fox\0jumps\0over\0the\0lazy\0dog\0\0"
n     : 7

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;
  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱读书的小胖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值