Strings in C
This is the fourth article of the series Learning C Programming Language.
But in C, is this possible ?
This question exists because C doesn't support string as its builtin data types like: char, int, float etc.
The answer is Yes. We can store strings in C using two ways
- char array (char []) and
- char pointer (char *)
Actually string in C means the characters stored in an array of char type.
There is a special character stored in every array at the ending of the array called NULL CHARACTER ( '\0') (back slash zero in single quotes).
Well, I am your coding buddy Vikas Patel (Village Programmer).
In this tutorial you will learn:
- Concept of strings in C.
- How to create strings in C ?
- How to store data in string ?
- How to display/use the string ?
- How to find length of the string ?
- How to reverse the string ?
🔅Concept of strings in C:
Strings in C are created using array. So, all the characters of the string are stored as individual elements in the array.
Ex. the string "Vikas" will be stored as;
stored "Vikas" as string in C |
string shown in an array |
Here '\0' which shows the end of the string.
🔅How to create strings in C:
You can create strings using char array and char pointer.
- Using char array:
char string[100];
- Using char pointer:
char *string;
🔅How to store data in strings in C:
To store data we can either directly store the data in the string.
- Using char array:
char name[] = {'V','i','k','a','s'};
- Using char pointer:
char *name = "Vikas";
🔅How to display string in C:
To use the string we can use as normal array or as pointer.
- To display on the terminal:
printf("name = %s",name);
- Or:
puts(name);
- Or print using loop:
for(i = 0;i<length;i++){ printf("%c",name[i]); }
🔅How to find length of string in C:
To find the length I've created a handy function called "slength" you can see the code below:
The function takes char * as argument and returns an int as the length of the string.
int slength(char *p){
int length = 0;
while (*p != '\0') {
++length;
++p;
}
return length;
}
🔅How to reverse a string in C:
To reverse I've a code here:
char * sreverse(char str[]){
int l, i, j = 0;
l = slength(str);
char *revstr; = (char *)malloc(l*sizeof(char));
for(i = l-1;i >= 0;i--){
revstr[j] = str[i];
j++;
}
return revstr;
}
To solve the problem of Array out of Index I've used Dynamic Memory allocation. (malloc()).
If you don't know about Dynamic memory allocation. Don't worry I'll write an article on it.
Complete code is here:
Download the code from 👉HERE .
Thanks for reading. 🙏
If you liked it feel free to share with your dear ones.💗
And tell me what do you think in the comment box.💬
إرسال تعليق