C Programming String Read Write Example

Declaration of String

Strings means the collection of characters or group of characters. i.e one dimensional array of characters is called as String. The difference between any other type of array and string is that a character array ends with a ‘\0’ as null character. It indicates the termination of valid characters in the array.

char str_name[]={‘D’,’I’,’G’,’I’,’T’,’A’,’L’,’\0′};

Here char array str_name is initialized to individual characters and last character we added is null character.

We can initialize the string as

char str_name []= “DIGITAL’;

Here ‘\0’ null character is placed implicitly. We can read or input string using gets function with spaces. scanf function can also be used with %s specifier. However, the scanf function terminates when it encounters a white space.

See following Example –

To Read & Write String using scanf , printf

Output

c-program-read-write-string
c-program-read-write-string

To Read and Write String using functions gets  and puts function.

Output

c-program-read-write-string-gets-puts
c-program-read-write-string-gets-puts

 

 

 

 

 

In this example , gets function is used to read string with white spaces.

How to Find length of String i.e Total number of characters in the string

To find number of characters , We can increment counter up to null character ‘\0’. We can use any looping statements to iterate in character array.

Here initial value of cnt variable is 0. While loop is used to iterate in the character array. The terminating condition is , check every character for null character ‘\0’.

If character is not null then increment counter variable when it reaches null character then exits the loop and show value of counter variable.

Counter variable cnt holds the total number of characters in the array which is the length of string.

Output

c-program-length-of-string
c-program-length-of-string