2012-11-11 62 views
-5

可能重复:
How to concatenate 2 strings in C?如何连接C中的字符串?

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

/* Function prototypes */ 
void wordLength (char *word); 
void wordConcat (char *wordC1, char *wordC2); 


int main (void) 
{ 
    int choice; 
    char word [20]; 
    char wordC1 [20]; 
    char wordC2 [20]; 

    printf("Choose a function by entering the corresponding number: \n" 
     "1) Determine if words are identical\n" 
     "2) Count number of words in sentence provided\n" 
     "3) Enter two strings to be strung together\n" 
     "4) Quit program\n"); 
    scanf("%d", &choice); 
    flushall(); 

    while (choice >= 1 && choice < 4) 
    { 
     /* if statements for appropriate user prompt and calls function */ 
     if (choice == 1) 
     { 
      /* gather user input */ 
     printf("\nYou have chosen to determine word length.\n" 
       "Please enter the word:\t"); 
      gets(word); 

      /* call function to output string as well as the string length */ 
      wordLength(word); 
     } 

     else if (choice == 2) 
     { 
      printf("\nYou have chosen to concatenate 2 words with a % symbol in between them.\n" 
       "Please enter word 1:\t"); 

      gets(wordC1); 

      printf("Please enter word 2:\t"); 

      gets(wordC2);      

      /* call function to output string as well as the string length */ 
      wordLength(word); 
     } 
    } 
} 

void wordLength(char *word) 
{ 
    int length; 

    printf("\nThe string entered is: %s\n\n", word); 

    length = strlen (word); 

    printf("The string length is: %d\n", length); 

    return; 
} 

void wordConcat(char *wordC1, char *wordC2) 
{ 
    printf("\nThe first word entered is: %s\n", wordC1); 
    printf("\nThe second word entered is: %s\n", wordC2); 
} 

我试图连接两个词从不同的字符串来。我似乎无法找到如何在MSDN库中执行此操作。它甚至存在于C中吗?或者你需要某种算法?这是如何完成的?

+2

使用'strcat()' – JonH

+2

查看'strcat()',并确保有足够的空间存储结果字符串,并且它是空的终止符。还要小心[Schlemiel the Painter](http://en.wikipedia.org/wiki/Schlemiel_the_Painter%27s_algorithm) –

+2

或'strncat()',这样更安全。 – jbowes

回答

0

strcat()是使用的标准功能,而且这个功能非常简单,通常用C编写,因此您可以轻松地从头开始编写它。