Strings in C Language
Strings in C Language
The string can be defined as the one-dimensional array of characters terminated by a null ('\0'). The character
array or the string is used to manipulate text such as word or sentences. Each character in the array occupies
one byte of memory, and the last character must always be 0. The termination character ('\0') is important
in a string since it is the only way to identify where the string ends. When we define a string as char s[10],
the character s[10] is implicitly initialized with the null in the memory.
• By char array
• By string literal
char ch[10]={'i', 'e', 'e', 'e', 'a', 'c', 'c', 'e', 's', 's', '\0'};
As we know, array index starts from 0, so it will be represented as in the figure given below.
While declaring string, size is not mandatory. So we can write the above code as given below:
char ch[]={'i', 'e', 'e', 'e', 'a', 'c', 'c', 'e', 's', 's', '\0'};
We can also define the string by the string literal in C language. For example:
char ch[]="ieeeaccess";
In such case, '\0' will be appended at the end of the string by the compiler.
tring literals can be assigned with a predefined size. But we should always account for one extra
space which will be assigned to the null character. If we want to store a string of size n then we
should always declare a string with a size equal to or greater than n+1.
char str[50] = "journal";
o We need to add the null character '\0' at the end of the array by ourself whereas, it is
appended internally by the compiler in the case of the character array.
o The string literal cannot be reassigned to another set of characters whereas, we can reassign
the characters of the array.
String Example in C
Let's see a simple example where a string is declared and being printed. The '%s' is used as a format
specifier for the string in c language.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[11]={ 'i', 'e', 'e', 'e', 'a', 'c', 'c', 'e', 's', 's', '\0'};
5. char ch2[11]=”Bangladesh";
6.
7. printf("Char Array Value is: %s\n", ch);
8. printf("String Literal Value is: %s\n", ch2);
9. return 0;
10. }
Traversing String
We need to know the length of the array to traverse an integer array, whereas we may use the null character
in the case of string to identify the end the string and terminate the loop.
There are two ways to traverse a string. By using the length of string and by using the null character.
1. #include<stdio.h>
2. void main ()
3. {
4. char s[11] = "ieeeaccess";
5. int i = 0;
6. int count = 0;
7. while(s[i] != NULL)
8. {
9. if(s[i]=='a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'u' || s[i] == 'o')
10. {
11. count ++;
12. }
13. i++;
14. }
15. printf("The number of vowels %d",count);
16. }
#include <stdio.h>
#include <string.h>
int main()
{
// declare and initialize string
char str[] = "Hello";
// print string
printf("%s\n", str);
int length = 0;
length = strlen(str);
// displaying the length of string
printf("Length of string str is %d", length);
return 0;
}
Note: The C language does not provide an inbuilt data type for strings but it has an access
specifier “%s” which can be used to print and read strings directly.
// C program to read string from user
#include<stdio.h>
int main()
{
// declaring string
char str[50];
// reading string
scanf("%s",str);
// print string
printf("%s",str);
return 0;
}
We know that the ‘&’ sign is used to provide the address of the variable to the scanf() function
to store the value read in memory. As str[] is a character array so using str without braces ‘[‘ and
‘]’ will give the base address of this string. That’s why we have not used ‘&’ in this case as we
are already providing the base address of the string to scanf.
// C program to illustrate how to
// pass string to functions
#include <stdio.h>
void printStr(char str[]) {
printf("String is : %s", str);
}
int main()
{
// declare and initialize string
char str[] = "Hello C";
// print string by passing string
// to a different function
printStr(str);
return 0;}
C gets() function
The gets() function enables the user to enter some characters followed by the enter key. All the characters
entered by the user get stored in a character array. The null character is added to the array to make it a
string. The gets() allows the user to enter the space-separated strings. It returns the string entered by the
user.
Declaration
char[] gets(char[]);
The gets() function is risky to use since it doesn't perform any array bound checking and keep
reading the characters until the new line (enter) is encountered. It suffers from buffer overflow,
which can be avoided by using fgets(). The fgets() makes sure that not more than the maximum
limit of characters are read. Consider the following example.
1. void main()
2. {
3. char str[20];
4. printf("Enter the string? ");
5. fgets(str, 20, stdin);
6. printf("%s", str);
7. }
Output
Enter the string? ieeeaccess is one of the best journal
ieeeaccess is one o
C puts() function
The puts() function is very much similar to printf() function. The puts() function is used to print
the string on the console which is previously read by using gets() or scanf() function. The puts()
function returns an integer value representing the number of characters being printed on the
console. Since, it prints an additional newline character with the string, which moves the cursor to
the new line on the console, the integer value returned by puts() will always be equal to the number
of characters present in the string plus 1.
Declaration
1. int puts(char[])
Let's see an example to read a string using gets() and print it on the console using puts().
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char name[50];
5. printf("Enter your name: ");
6. gets(name); //reads string from user
7. printf("Your name is: ");
8. puts(name); //displays string
9. return 0;
10. }
Functions in Strings
strlen() function in c: The strlen() function calculates the length of a given string.
The strlen() function is defined in string.h header file. returns the length of the given string. It
doesn’t count null character ‘\0’.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={ 'i', 'e', 'e', 'e', 'a', 'c', 'c', 'e', 's', 's', '\0'};
5. printf("Length of string is: %d",strlen(ch));
6. char str[]= "hello";
7. printf("Length of string is: %d", strlen(str));
8. return 0;
9. }
C Copy String: strcpy(): The strcpy(destination, source) function copies the source string in
destination.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[20]={ ]={ 'i', 'e', 'e', 'e', 'a', 'c', 'c', 'e', 's', 's','\0'};
5. char ch2[20];
6. strcpy(ch2,ch);
7. printf("Value of second string is: %s",ch2);
8. return 0;
9. }
C String Concatenation: strcat(): The strcat(first_string, second_string) function concatenates
two strings and result is returned to first_string.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char ch[10]={'h', 'e', 'l', 'l', 'o', '\0'};
5. char ch2[10]={'c', '\0'};
6. strcat(ch,ch2);
7. printf("Value of first string is: %s",ch);
8. return 0;
9. }
C Compare String: strcmp(): The strcmp(first_string, second_string) function compares two
string and returns 0 if both strings are equal.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str1[20], str2[20];
5. printf("Enter 1st string: ");
6. gets(str1);//reads string from console
7. printf("Enter 2nd string: ");
8. gets(str2);
9. if(strcmp(str1, str2)==0)
10. printf("Strings are equal");
11. else
12. printf("Strings are not equal");
13. return 0;
14. }
C Reverse String: strrev(): The strrev(string) function returns reverse of the given string. Let's
see a simple example of strrev() function.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nReverse String is: %s",strrev(str));
9. return 0;
10. }
C String Lowercase: strlwr(): The strlwr(string) function returns string characters in lowercase.
Let's see a simple example of strlwr() function.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str); //reads string from console
7. printf("String is: %s",str);
8. printf("\nLower String is: %s",strlwr(str));
9. return 0;
10. }
C String Uppercase: strupr(): The strupr(string) function returns string characters in uppercase.
Let's see a simple example of strupr() function.
1. #include<stdio.h>
2. #include <string.h>
3. int main(){
4. char str[20];
5. printf("Enter string: ");
6. gets(str);//reads string from console
7. printf("String is: %s",str);
8. printf("\nUpper String is: %s",strupr(str));
9. return 0;
10. }
ded: 0.37%
C Math
C Programming allows us to perform mathematical operations through the functions defined in
<math.h> header file. The <math.h> header file contains various methods for performing
mathematical operations such as sqrt(), pow(), ceil(), floor() etc.
C Math Functions
There are various methods in math.h header file. The commonly used functions of math.h header
file are given below.
1) ceil(number) rounds up the given number. It returns the integer value which is
greater than or equal to given number.
2) floor(number) rounds down the given number. It returns the integer value which is
less than or equal to given number.
1. #include<stdio.h>
2. #include <math.h>
3. int main(){
4. printf("\n%f",ceil(3.6));
5. printf("\n%f",ceil(3.3));
6. printf("\n%f",floor(3.6));
7. printf("\n%f",floor(3.2));
8. printf("\n%f",sqrt(16));
9. printf("\n%f",sqrt(7));
10. printf("\n%f",pow(2,4));
11. printf("\n%f",pow(3,3));
12. printf("\n%d",abs(-12));
13. return 0;
14. }
8. Â
9. Fullscreen
10. Backward Skip 10sPlay VideoForward Skip 10s