首页 > 解决方案 > 将第二个字符串放在第一个字符串上用户输入的位置

问题描述

我开始学习 C,如果我的作业有任何帮助,我将不胜感激。我需要制作一个从用户输入中获取 2 个字符串和一个位置的函数。第二根弦必须在第一根弦的位置上。例如:

我需要让它与 VisualStudio 一起工作,这就是“_s”的原因。调试器说我在“strcat”和“strcpy”行上“没有足够的信息”。

这是我的代码不起作用:

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

void concStrings(char  string1[], char string2[], int pos);

int main(void) {
    char lastName[20] = { '\0' };
    char firstName[20] = { '\0' };
    int pos = 0;
    scanf_s("%s", &firstName, 20);
    scanf_s("%s", &lastName, 20);
    scanf_s("%d", &pos);
    concStrings(firstName, lastName, pos);
    printf("%s\n", firstName);
    return 0;
}
// Here is my funcion
void concStrings(char  string1[], char string2[], int pos){
    char tmp[40];
    strcpy_s(tmp, string1, pos);
    strcat_s(tmp, string2);
    strcat_s(tmp, &string1[pos]);
    strcpy_s(string1, tmp);
}

标签: cstring-concatenationc-strings

解决方案


对于初学者来说,这些调用中的第二个参数

scanf_s("%s", &firstName, 20);
scanf_s("%s", &lastName, 20);

指定不正确。它应该被指定为

scanf_s("%s", firstName, 20);
scanf_s("%s", lastName, 20);

因为第二个函数参数的类型是char *,并且用作参数的数组名称已经隐式转换为指向它们的第一个元素的指针。

请注意,标题<stdlib.h>在您的程序中是多余的。没有使用来自标头的声明。

无需定义辅助数组,而且无需使用像 40 这样的幻数来执行任务。

函数本身应该具有与大多数 C 字符串函数一样的返回类型 char *。该函数也不应该检查第一个字符数组中是否有足够的空间来容纳存储在第二个字符数组中的字符串。应该保证这一点的是功能的客户端。

此外,如果指定的位置大于第一个字符串的长度,那么函数应该在这种情况下做一些事情。一种合乎逻辑的方法是将第二个字符串附加到第一个字符串。

这是一个演示程序,显示了如何定义函数。

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

char * concStrings( char *s1, const char *s2, size_t pos )
{
    size_t n1 = strlen( s1 );

    if ( !( pos < n1 ) )
    {
        strcat( s1, s2 );
    }
    else
    {
        size_t n2 = strlen( s2 );
        memmove( s1 + pos + n2, s1 + pos, n1 - pos + 1 );
        memcpy( s1 + pos, s2, n2 );
    }

    return s1;
}

int main(void) 
{
    enum { N = 20 };
    char s1[N] = "Chocolate";
    char s2[] = "Cake";
    size_t pos = 3;

    if ( strlen( s1 ) + strlen( s2 ) < N )
    {
        puts( concStrings( s1, s2, pos ) );
    }
    else
    {
        puts( "Unable to include one string in another: not enough space>" );
    }

    return 0;
}

它的输出是

ChoCakecolate

推荐阅读