A string is a sequence of characters that are treated as a single data item and terminated by a null character '\0'
. Remember that the C language does not support strings as a data type. A string is actually a one-dimensional array of characters in the C language. These are often used to create meaningful and readable programs.
If you don't know what an array in C means, you can check the C Array tutorial to know about Array in the C language.
For example, The string "home" contains 5 characters including the '\0'
character which is automatically added by the compiler at the end of the string.
Declaring and Initializing string variables:
String Input and Output:
%s format specifier to read a string input from the terminal.
But scanf() function, terminates its input on the first white space it encounters.
edit set conversion code %[..] that can be used to read a line containing a variety of characters, including white spaces.
The
gets()
the function can also be used to read character strings with white spaces
String Handling Functions:
C language supports a large number of string handling functions that can be used to carry out many of the string manipulations. These functions are packaged in the string.h library. Hence, you must include string.h header file in your programs to use these functions.
The following are the most commonly used string handling functions.
Method | Description |
---|---|
strcat() | It is used to concatenate(combine) two strings |
strlen() | It is used to show the length of a string |
| It is used to show the reverse of a string |
strcpy() | Copies one string into another |
strcmp() | It is used to compare two string |
strcat()
function in C:
Syntax:
strcat()
will add the string "World" to "Hello" i.e output = HelloWorld.
strlen()
and strcmp()
function:
strlen()
will return the length of the string passed to it and strcmp()
will return the ASCII difference between the first unmatching character of two strings.
OUTPUT: 12 -1
strcpy()
function:
It copies the second string argument to the first string argument.
Example of strcpy()
function:
OUTPUT: StudyTonight
strrev()
function:
It is used to reverse the given string expression.
Code snippet for strrev()
:
OUTPUT: Enter your string: studytonight Your reverse string is: thginotyduts
No comments:
Post a Comment