Learn C - C String






A string constant is a sequence of characters between a pair of double-quote characters.

Anything between a pair of double quotes is interpreted by the compiler as a string.

The following statements illustrate this:

printf("This is a string.");
printf("This is on\ntwo lines!");
printf("For \" you write \\\".");

We can add a \0 character to the end of a string explicitly.


#include <stdio.h>

int main(void)
{
  printf("The character \0 is used to terminate a string.");
  return 0;
}

The code above generates the following result.





Variables That Store Strings

C has no string variable types and there are no special operators for processing strings.

C standard library provides an range of functions to handle strings.

You use an array of type char to hold strings.

You can declare an array variable like this:

char my_string[20];

This variable can accommodate a string that contains up to 19 characters, because you must allow one element for the termination character.

You could use this array to store 20 characters that are not a string.

The compiler automatically adds \0 to the end of every string constant.

You can initialize a string variable when you declare it:

char my_string[] = "This is a string.";

Here you haven't explicitly defined the array dimension.

The compiler will assign a value to the dimension that is sufficient to accommodate the initializing string constant.

In this case it will be 18. 17 elements are for the characters and an extra element is for the terminating \0.

You can initialize part of an array of elements of type char with a string.

For example:

char str[40] = "To be";

The compiler will initialize the first five elements, str[0] to str[4], with the characters of the string constant, and str[5] will contain the null character, '\0'.

Memory space is allocated for all 40 elements of the array.

Initializing a char array and declaring it as constant is a good way of handling standard messages:

const char message[] = "This is a test.";

To refer to the string stored in an array, use the array name by itself.

For instance, to output the string stored in message using the printf() function, you could write this:

printf("\nThe message is: %s", message);

The %s specification is for outputting a null-terminated string.

string formatting


  #include <stdio.h> 
  #define BLURB "Authentic imitation!" 
  int main(void) 
  { //  w w  w .j  a  v a  2s.com
      printf("[%2s]\n", BLURB); 
      printf("[%24s]\n", BLURB); 
      printf("[%24.5s]\n", BLURB); 
      printf("[%-24.5s]\n", BLURB); 
   
      return 0; 
  }    

The code above generates the following result.





Example

The following code shows how to get the length of a string.


#include <stdio.h>
int main(void)     {
  char str1[] = "This is a test.";
  char str2[] = "This is another test.";
  unsigned int count = 0;                // Stores the string length
/*w ww  .  j  av a2 s .  com*/
  while (str1[count] != '\0')            // Increment count till we reach the
    ++count;                             // terminating character.

  printf("The length of the string \"%s\" is %d characters.\n", str1, count);

  count = 0;                             // Reset count for next string
  while (str2[count] != '\0')            // Count characters in second string
    ++count;

  printf("The length of the string \"%s\" is %d characters.\n", str2, count);
  return 0;
}

The code above generates the following result.

Arrays of Strings

You can store a whole bunch of strings and refer to any of them through a single variable name.

char my_strings[3][32] = {
                        "Hi",
                        "Hello.",
                        "How are you."
                      };

Although you must specify the second dimension in an array of strings, you can leave it to the compiler to figure out how many strings there are. You could write the previous definition as:

char my_strings[][32] = {
                       "Hi",
                        "Hello.",
                        "How are you."
                     };

You could output the three my_strings with the following code:

for(unsigned int i = 0 ; i < sizeof(my_strings)/ sizeof(my_strings[0]) ; ++i)
  printf("%s\n", my_strings[i]);

The following code shows how to find the number of strings in a two-dimensional array and the length of each string:


    #include <stdio.h>
/*from w ww .  j av  a  2s  . co  m*/
    int main(void)
    {
      char str[][70] =  {
                  "hi",
                  "java2s.com",
                  "this is a test.",
                        };
      unsigned int count = 0;                              // Length of a string
      unsigned int strCount = sizeof(str)/sizeof(str[0]);  // Number of strings
      printf("There are %u strings.\n", strCount);

      // find the lengths of the strings
      for(unsigned int i = 0 ; i < strCount ; ++i)
      {
        count = 0;
        while (str[i][count])
          ++count;

        printf("The string:\n    \"%s\"\n contains %u characters.\n", str[i], count);
      }
      return 0;
    }

The code above generates the following result.