Society & Lifestyle
|Computing||Share This Page|
Handling of Character Strings
|by Sachin Mehta|
A string is a collection of characters. In terms of programming, it can be defined as an array of characters. Any group of characters (except double quote sign) defined between double quote marks is a constant string. For example, if the following string
has to be displayed on the screen, then we will give
in the program. The " is to print the double quote itself onto the screen.
The common operations related to character strings are:
String variables are declared similar to any other array variables in C. For example if we want to declare a string variable str of a maximum size of 8 characters, then it can be done as follows
When the compiler assigns a character string to a character array, it automatically supplies a null character ('') at the end of the string. So the size of string should be such that it can hold the entire string plus one null character.
In order to avoid the confusion we can give initializations without specifying the array size. For example:
This will define a string of five elements.
Reading strings from terminal
The function scanf with the %s format allows us to read a word input by the user, the same way as integers , real values & characters are read using %d, %f & %c respectively.
Dissimilar to the integer , float & characters the %s format doesnt require the ampersand before the variable name. The main problem is, that the scanf stops reading a string of characters when it encounters the first white space. So if we give for above example
Then the scanf statement will read only Sachin into the variable name.
In many text processing applications, we need to read an entire line of text. In that case as we can't use scanf statement, we can always use the getchar funtion to read the entire line or word as follows
Writing strings to screen
We have seen how we can use printf statement to directly output the string within double quotes to the screen. Now we will see the outputting of strings using string variables. For example the contents of the variable name can be printed as
We also have something called the precision with which the string variable has to printed out.
This specifies that only the first 3 characters have to be printed in a total field width of 7 characters & right justified in the allocated width by default. We can include a minus sign to make it left justified(%-7.3).
The following points should be noted
We will see rest of the topics related to strings in the next article.
|More by : Sachin Mehta|
|Views: 3026 Comments: 1|
Comments on this Article
09/30/2010 03:33 AM
|Top | Computing|