连接一个单词n次

时间:2015-09-27 20:08:25

标签: c string-concatenation

我该怎么办?

x = abc
x^1 = abc
x^2 = abcabc
x^3 = abcabcabc

我尝试在strcat循环中使用for函数,但它不起作用。

int potw2;
char w2[100];
w2="abc";
potw2 = 5;
potenciarw2(w2, potw2);
void potenciarw2(char *pal, int potw2) {
    for (int i = 0 ; i < potw2 ; i++) {
        strcat(pal, pal);
    }
    printf("La palabra es:%s\n",pal);       
}

3 个答案:

答案 0 :(得分:4)

strcat()预计目标和来源重叠。换句话说,strcat()的两个参数都不能指向相同的内存。

您需要为结果字符串分配新内存,并在循环中使用memcpy

void potenciarw2(char *pal, int potw2)
{
    size_t len = strlen(pal);
    char* result = malloc(len * potw2 + 1); // allocate enough memory for the resulting string and null char
    if (result == NULL) {
        fputs("malloc() ha fallado", stdout);
        return;
    }

    for (int i = 0 ; i < potw2 ; i++) {
        memcpy(result + i * len, pal, len); // concatenate string using memcpy
    }

    result[len * potw2] = '\0'; // terminate with null char

    printf("La palabra es:%s\n",result);

    free(result);
}

答案 1 :(得分:2)

不要使用strcat(),我的意思是对于已知长度的字符串的增量连接,我几乎无法想到strcat()真正有用的情况,有些情况但一般情况下,这会更好,更有效,例如

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

char *pow_string(const char *const source, int times)
{
    size_t length;
    char *result;
    length = strlen(source);
    result = malloc(length * times + 1);
    if (result == NULL)
        return NULL;
    for (int index = 0 ; index < times ; ++index)
        memcpy(result + index * length, source, length);
    result[length * times] = '\0';
    return result;
}

int
input_error()
{
    fprintf(stderr, "error de entrada, ha introducido texto inválido\n");
    return -1;
}

int
main(void)
{
    char *result;
    int power;
    char word[100];
    fprintf(stdout, "Ingrese un texto (máx 99 caracteres) > ");
    if (scanf("%99[^\n]", word) != 1)
        return input_error();
    fprintf(stdout, "Cuántas veces quiere repetir la palabra ? ");
    if (scanf("%d%*[ \t]", &power) != 1)
        return input_error();
    result = pow_string(word, power);
    if (result == NULL)
        return -1;
    fprintf(stdout, "%s\n", result);
    /* free `result' which was allocated with `malloc()' */
    free(result);
    return 0;
}

答案 2 :(得分:1)

您的功能需要进行一些修改才能正常工作。这是修改:

void potenciarw2(char *pal, int potw2) {

    /* allocate some memory and copy to it*/
    char buffer[100];

    strcpy(buffer,pal);

    for (int i = 0 ; i < potw2 ; i++) {
        strcat(buffer, pal);/*now you can use strcat() safely*/
    }

    /*copy data back to pal*/
    strcpy(pal,buffer);
    printf("La palabra es:%s\n",pal);       
}

int main(void)
{

    int potw2;
    char w2[100] = "abc";
    potw2 = 3;
    potenciarw2(w2, potw2);

}