2013-12-09 2 views
1

누군가이 프로그램을 도와 줄 수 있는지 궁금합니다. 두 개의 문자열을 취하는 함수를 작성하십시오. 이 함수는 두 문자열을 사전 사전 식으로 오는 문자열과 결합해야합니다. 두 문자열 사이에 공백이 있어야합니다. 결과 문자열을 한 줄에 인쇄하십시오. 결과 문자열의 길이를 한 줄에 인쇄하십시오.비교, 결합 및 문자열 길이 결정?

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

int main(){ 

char word1[10]; 
char word2[10]; 
int length; 

//getting the words from input given by the user 
printf("Enter the first word. (10 Letters or less)\n"); 
scanf("%s", word1); 
printf("Enter the second word. (10 Letters or less)\n"); 
scanf("%s", word2); 

//comparing the two words entered 
if (strcmp(word1, word2)>0) 
    printf("%s comes before %s\n", word2, word1); 
else if (strcmp(word1, word2)<0) 
    printf("%s comes before %s\n", word1, word2); 
else 
    printf("Both words are the same!\n"); 

//combining the two words 
strcat(word1, " "); 
strcat(word1, word2); 
printf("\n%s\n", word1); 

//looking at the length of the two words 
length = strlen(word1) + strlen(word2) - 1; 
printf("The length of the words are %d.\n", length); 

return 0; 
} 

이것이 내 코드입니다. 나는 내 자신의 시각화를 위해 어느 단어가 먼저 올지를 인쇄하기로 결정했다. 어휘 사전을 처음으로 먼저 쓰는 방법과 두 결과 조합의 길이를 결정하는 방법을 조합하는 방법은 확실하지 않습니다. 나는 빼기 1을 덧붙이면 단어를 결합 할 때 공백의 효과를 꺼내 겠지만 문자열 길이는 프로그램에 다른 단어를 넣을 때 항상 다른 숫자에 의해 꺼져 있다고 생각했습니다. 도움이된다면 고맙겠습니다. 감사합니다.

+0

word1''에 충분한 길이 없다. 또한'strlen (word2)'를 추가하지 말고 word1은 word2를 포함합니다. – BLUEPIXY

답변

0

발신자와 메모리 할당을 나뭇잎 버전 :이 같은

/** Return 0 if not enough space, else length of resultant string. */ 
int stringOrder(const char * const str1, const char * const str2, char* retBuf, int bufLen) 
{ 
    const char* first = str1; 
    const char* second = str2; 
    int requiredLength = strlen(str1) + strlen(str2) + 2; 

    if (requiredLength > bufLen) 
     return 0; 

    if(strcmp(str1, str2) == 1) 
    { 
     first = str2; 
     second = str1; 
    } 

    strcpy(retBuf, first); 
    strcat(retBuf, " "); 
    strcat(retBuf, second); 

    return requiredLength - 1; 
} 

사용법 :

#define LENGTH 128 
    const char* str1 = "world"; 
    const char* str2 = "hello"; 

    char result[128] = ""; 

    int ok = stringOrder(str1, str2, result, LENGTH); 

    if (ok) 
     printf("%s\n", result); 
    else 
     printf("Not enough space");