91-9990449935 0120-4256464 |
C StringsString in C language is an array of characters that is terminated by \0 (null character). There are two ways to declare string in c language.
Let's see the example of declaring string by char array in C language. As you know well, array index starts from 0, so it will be represented as in the figure given below. While declaring string, size is not mandatory. So you can write the above code as given below: You can also define string by string literal in C language. For example: In such case, '\0' will be appended at the end of string by the compiler. Difference between char array and string literalThe only difference is that string literal cannot be changed whereas string declared by char array can be changed. String Example in CLet's see a simple example to declare and print string. The '%s' is used to print string in c language. Output: Char Array Value is: javatpoint String Literal Value is: javatpoint C String FunctionsThere are many important string functions defined in "string.h" library.
1) C String Length: strlen()The strlen() function returns the length of the given string. It doesn't count null character '\0'. Output: Length of string is: 10 2) C Copying String: strcpy()The strcpy(destination, source) function copies the source string in destination. Output: Value of second string is: javatpoint 3) C String Concatenation: strcat()The strcat(first_string, second_string) function concatenates two strings and result is returned to first_string. Output: Value of first string is: helloc 4) C String Comparision: strcmp()The strcmp(first_string, second_string) function compares two string and returns 0 if both strings are equal. Here, we are using gets() function which reads string from the console. Output: Enter 1st string: hello Enter 2nd string: hello Strings are equal
Next TopicStructure in C
|