Concepts:
String and library functions for their manipulation (library string.h
)
Text:
Implements a C program that:
str1
and str2
of dimension N
e str3
whose dimension is obtaining directly during its initialization.str3
str1
str1
in str2
str2
str2
str2
writing the character '\0' in place of the fourth character of str2
str2
str1
and str2
, printing if they are equal or different
Solution:
/* Example about the utilization of strings and the string.h library */ #include <stdio.h> #include <string.h> #define N 20 int main(){ char str1[N], str2[N], str3[]="abc"; printf("STR3 : %s\n", str3); /*scanf("%s", str1);*/ /* Read only a word */ gets(str1); /* Read the whole line */ printf("STR1 : %s\n", str1); strcpy(str2, str1); /* Copy the content of str1 in str2 */ printf("STR2 : %s\n", str2); printf("LEN : %d\n", (int)strlen(str2)); /* strlen returns the length of a string */ str2[3] = '\0'; /* Writes the end-of-string character '\0' in the position number 3 of the array of character. The string is truncated at position 2 (the resulting string is therefore formed by only 3 characters) */ printf("STR2b: %s\n", str2 ); if (strcmp(str1, str2)==0){ /* The function strcmp returns 0 if the two strings are equals, a value other than 0 if they are different (<0 if str1 is less than str2, >0 if str1 is greater than str2 */ printf("str1 is equal to str2\n"); }else{ printf("str1 different from str2\n"); } return 0; }