User Tools

Site Tools


cs:c_language:strings_1
Site was transfered to www.skenz.it
Please, always refer to this link with the following URL: https://www.skenz.it/cs/c_language/strings_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:

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;
}

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

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
/membri/wiki/data/pages/cs/c_language/strings_1.txt · Last modified: 2015/10/28 15:23 (external edit)


Policy sui Cookie