编写一个函数,它从一个字符串中提取一个子字符串

<p>函数原型如下:</p><p>int substr(char dst[], char src[],int start, int len)</p><p>{}</p><p>	目标是:从<span style="font-family:Times New Roman;">src</span><span style="font-family:宋体;">数组起始位置向后偏移</span><span style="font-family:Times New Roman;">start</span><span style="font-family:宋体;">个字符的位置开始,最多复制</span><span style="font-family:Times New Roman;">len</span><span style="font-family:宋体;">个非</span><span style="font-family:Times New Roman;">NUL</span><span style="font-family:宋体;">字符到</span><span style="font-family:Times New Roman;">dst</span><span style="font-family:宋体;">数组。在复制完毕之后,</span><span style="font-family:Times New Roman;">dst</span><span style="font-family:宋体;">数组必须以</span><span style="font-family:Times New Roman;">NUL</span><span style="font-family:宋体;">字节结尾。函数的返回值是存储于</span><span style="font-family:Times New Roman;">dst</span><span style="font-family:宋体;">数组中的字符串的长度。</span></p>





#include <stdio.h>
#include <string.h>

int substr(char dst[], char src[],int start, int len)
{
    int i=0;
    int n;
    char *p=src + start;
    n = strlen(p);

    if(len>n)
    {
        len=n;
    }

    while(len)
    {
        dst[i]=src[start+i];
        len--;
        i++;
    }
    dst[i]='\0';

    return strlen(dst);
}

int main()
{
    char a[]="message";
    char b[10];
    int start=2,len=5;

    printf("%d\n",substr(b,a,start,len));
    printf("%s\n",b);

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值