2012-11-11 7 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로 작성되므로 처음부터 쉽게 작성할 수 있습니다.

관련 문제