User Tools

Site Tools


cs:c_language:strings_1
Return to Home page
no way to compare when less than two revisions

Differences

This shows you the differences between two versions of the page.


cs:c_language:strings_1 [2024/04/08 22:35] (current) – created - external edit 127.0.0.1
Line 1: Line 1:
 +====== Strings (Example 1) ======
 +**Concepts:**\\
 +String and library functions for their manipulation (library ''string.h'')
  
 +**Text:**\\
 +Implements a C program that:
 +  * declares three strings (i.e., arrays of characters), ''str1'' and ''str2'' of dimension ''N'' e ''str3'' whose dimension is obtaining directly during its initialization.
 +  * prints ''str3''
 +  * acquires a string in ''str1''
 +  * copy ''str1'' in ''str2''
 +  * prints ''str2''
 +  * prints the length of ''str2''
 +  * reduces the dimension of ''str2'' writing the character '\0' in place of the fourth character of ''str2''
 +  * prints the new obtained string ''str2''
 +  * compares the content of ''str1'' and ''str2'', printing if they are equal or different
 +
 +**Solution:**\\
 +<file C string_1.c>
 +/*
 +  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;
 +}
 +</file>

If you found any error, or if you want to partecipate to the editing of this wiki, please contact: admin [at] skenz.it

You can reuse, distribute or modify the content of this page, but you must cite in any document (or webpage) this url: https://www.skenz.it/cs/c_language/strings_1?do=diff&rev2%5B0%5D=&rev2%5B1%5D=1551188114&difftype=sidebyside
/web/htdocs/www.skenz.it/home/data/pages/cs/c_language/strings_1.txt · Last modified: 2024/04/08 22:35 by 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki
Privacy Policy