User Tools

Site Tools

Return to Home page

Strings (Example 1)

String and library functions for their manipulation (library string.h)

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


  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");
    printf("str1 different from str2\n");
  return 0;

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

You can reuse, distribute or modify the content of this page, but you must cite in any document (or webpage) this url:
/web/htdocs/ · Last modified: 2024/04/08 22:35 by

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