连接两个单独字符串的前半部分

时间:2016-03-09 00:36:07

标签: c

如何编写从用户接受两个字符串的C程序并打印一个字符串,该字符串是两个字符串前半部分串联的结果。对于奇数长度的字符串,额外的字符位于字符串的前半部分。

到目前为止我有这个但是对于分成两部分感到困惑......

printf("Please enter your first word.\n"); //Asks for first string

scanf("%s",&c); //Takes first string

printf("Please enter your second word.\n"); //Asks for second string

scanf("%s",&d); //Takes second string

strcat(c,d); //Combines both strings

2 个答案:

答案 0 :(得分:0)

void concathalf(const char *a, const char *b, char *out)
{
    char *abuf, *bbuf;

    if ((abuf = malloc(strlen(a) / 2)) && (bbuf = malloc(strlen(b) / 2))) {
        memcpy(abuf, a, strlen(a) / 2);
        memcpy(bbuf, b, strlen(b) / 2);

        abuf[strlen(a) / 2] = bbuf[strlen(b) / 2] = 0;
    }
    sprintf(out, "%s%s", abuf, bbuf);
    free(abuf);
    free(bbuf);
}

现在,处理奇数长度输入将留作练习。

答案 1 :(得分:0)

如果你只是想打印出结果而不是关心字符串c和d的内容,你可以做一些像

这样的事情。
#include <stdio.h>
#include <string.h>

int main(void) {
    char c[1024];       // c string buffer
    char d[1024];       // d string buffer

    // initialize to empty strings
    c[0] = '\0';
    d[0] = '\0';    

    // read strings c and d
    scanf("%s", c);
    scanf("%s", d);

    // just to make sure there is no overflow
    c[1023] = '\0';
    d[1023] = '\0';

    // cut strings in middle
    c[(strlen(c) + 1)/2] = '\0';
    d[(strlen(d) + 1)/2] = '\0';

    // print final string
    printf("%s", c);
    printf("%s\n", d);

    return 0;

}

(strlen(c)+ 1)/ 2的结果符合你的要求,因为它执行整数除法。如果strlen(c)给出偶数大小,那么加1会使它成为下一个奇数,对整数除法没有影响。如果另一方面,数字是奇数,添加一个将使它成为下一个甚至实现你需要的四舍五入。 &#39; \ 0&#39;将确保该字符串在该点终止。

如果您不想丢失两个字符串的信息或需要存储的结果字符串,那么您可以执行类似

的操作
#include <stdio.h>
#include <string.h>

int main(void) {
    char c[1024];       // c string buffer
    char d[1024];       // d string buffer
    char r[1024];       // resulting string buffer
    int i;              // general counter
    int c_half_len;     // c half length
    int d_half_len;     // d half length

    // initialize to empty strings
    c[0] = '\0';
    d[0] = '\0';
    r[0] = '\0';        

    // read strings c and d
    scanf("%s", c);
    scanf("%s", d);

    // just to make sure there is no overflow
    c[1023] = '\0';
    d[1023] = '\0';

    // get c and d half lengths rounding up
    c_half_len = (strlen(c) + 1)/2;
    d_half_len = (strlen(d) + 1)/2;

    // copy first half c string to begining of result
    for (i = 0; i < c_half_len; ++i) {
        r[i] = c[i];
    }

    // copy first half d string after the end of the first half string
    for (i = 0; i < d_half_len; ++i) {
        r[c_half_len + i] = d[i];
    }

    // add an end of string character
    r[c_half_len + d_half_len] = '\0';

    // print final string
    printf("%s\n", r);

    return 0;

}

在这两种情况下,我都假设两个字符串具有最大长度,在本例中为1024(包括字符串字符的结尾)。如果不是这种情况,那么你需要使用动态内存来处理事情。

相关问题