Tuesday, August 16, 2011

C Programming: Strings

iA string is a sequence of characters( Array of character)  that is treated as a single data item. Any group of characters (except double quote sign) defined between double quotation marks is a string constant. Example:

“All is Well”

If you want to include a double quote in the string to be printed, then you may use it with a back slash as shown below:

“\”All is Well, \” said Amir Khan.”

Declaring String Variables

C does not support strings as a data type as C++, JAVA etc. However, it allows us to represent strings as character arrays. In C, therefore, a string variable is any valid C variable name and is always declared as an array of characters. The general syntax of declaration of string is:

char string_name [ size];

The size determines the number of characters in the string_name. Example: char city[20]; When the compiler assigns a character string to a character array, it automatically supplies a null character(‘\0’) at the end of the string. Therefore, the size should be equal to the maximum number of characters in the string plus one.

Initializing string variable 

C permits a character array to be initialized in either of the following two forms:

  1: char city[10] = "Kathmandu";
  2: char city[10] = {'K','a','t','h','m','a','n','d','u','\0'};

The reason that city had to be 10 elements long is that the string Kathmandu contains 9 characters and one element space is provided for the null terminator.

Reading String from user

The familiar input function scanf can be used with %s format specification to read in a string of characters. Example:

char address[10];

Note that there is no amp percent(&) before address , it is because address itself represents the first address of string. The problem with scanf with %s  is that it terminates its input on the first white space it finds. For example if I enter NEW YORK, then it only takes NEW as input and neglects YORK. To avoid this you can write following code to read input

  1: char address[10];
  2: scanf("%[^\n]", address];
  3: gets(address)

You can either use scanf with %[^\n] as format specification or use gets(string_name).

No comments:

Post a Comment