不适用string.h库函数的字符串相连接

解题思路:
1.通过键盘输入两个字符串。这两个字符串的长度由读者输入
2.输入相应的字符串,通过比较输入字符串的长度是否超出了读者输入的数字。超出则提示并需要读者继续输入,知道成功为止
3.开辟一个数组空间,利用输入字符串的长度进行控制。并在长度数值上加1,以保证字符串的完整性和内存分配的正常
4.通过for进行字符串的链接

/*****************************************
FileName:/mnt/hgfs/share/homework/saddle.c
Author:
E_mail:469139522@qq.com  2016-03-22 02:21
*****************************************/

#include <stdio.h>

int main(int argc,char **agrv)
{
    int num1,num2,i,j=0;
    int count=0;
    int n=0,m=0;
    printf("enter the first space of s1:\t");
    scanf("%d",&num1);
    char s1[num1];

    printf("enter the second space of s2:\t");
    scanf("%d",&num2);
    char s2[num2];

    printf("enter the first string:\t\t");
        scanf("%s",s1);
    for(i=0;s1[i]!='\0';i++)
    {
        n++;
    }
    while(n>num1)
    {
        printf("string <s1> is too long\n");
        printf("enter the first string:\t\t");
        scanf("%s",s1);
        for(n=0,i=0;s1[i]!='\0';i++)
        {
            n++;
        }
        if(n<num1)
            break;
    }


    printf("enter the second string:\t");
    scanf("%s",s2);
    for(i=0;s2[i]!='\0';i++)
    {
        m++;
    }
    if(m>num2)
    {
        printf("string <s2> is too long\n");

    }

    while(m>num2)
    {
        printf("enter the second string:\t");
        scanf("%s",s2);
        for(m=0,i=0;s2[i]!='\0';i++)
        {
            m++;
        }
        if(m<num2)
            break;
    }


    printf("\nEnter Successfully!\n");

    char s3[m+n+1];//open a space which can contain <s1>and <s2>,but we can't ingore the '\0' in the end!


    for(i = 0;s1[i] != '\0';i++,j++)
    {
        s3[j]=s1[i];
    }

    for(i = 0;s2[i] != '\0';i++,j++)
    {
        s3[j]=s2[i];
    }
    s3[j]='\0';

    printf("string_cat is:\t%s\n\n",s3);
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值