Strings in C

  • String = a sequence of characters

  • The C programming language does not have a String data type

      • A string in C is stored as an array of char

  • There are 2 ways to represent strings inside the computer:

      1. Using its location in memory + its length   (e.g.: Java)

      2. Using its location in memory + a sentinel   (e.g.: C)

     

     

The representation of strings in C

  • Representation of strings in C:

      • A string is stored in memory using consecutive memory cells

      • A string is terminated by the sentinel '\0' (known as the NUL character).

    Example: how the string "Hello" is stored in C

String variables in C

  • A string variable is just an array of char in C

    Example:

       char line[11];  // Can store a string of 10 chars
                       // The sentinel '\0' takes up 1 char

  • Example using a string variable:

       int main(int argc, char *argv[])
       {
          char a[10] = { 'H', 'e', 'l', 'l', 'o', '\0' } ; 
                       // Don't forget the sentinel '\0'
    	           // used to end the string !
    
          printf("String a = %s\n", a ); // Print string
          printf("Quiz: %s\n", &a[1] );  // Print ???  
       }

DEMO: demo/C/set2/string2.c

Functions with string parameters

  • Function printStr(s) will print the input string s:

       void printStr( char s[] )  // A string is the location of a char[ ]
       {
          printf( "string = %s\n", s);
       }

  • Since s[ ] is equivalent to *s in C, we can also write:

       void printStr( char *s )  //  A string is the location of a char
       {
          printf( "string = %s\n", s);
       }

DEMO: demo/C/set2/string4.c

String constants in C

  • A string constant, such as:

       "Hello"
    
        
    
    

    will evaluate to the memory location where the string is stored

  • The data type of a string constant is:   char * (reference to a char)

String functions in C's library

  • The C standard library contains many functions that manipulate strings

      • I will discuss a few of these functions

        .....and also explain the internal details

  • C is not the best language if you need to manupilate strings frequently

  • In stead, I would recommend you use C++ because:

      • C++ has a string class with extensive support for string manipulation