Learn C Programming Lesson 7 - Strings
A string is an array of characters. Strings must have a 0 or null character after the last character to show where the string ends. The null character is not included in the string.
There are 2 ways of using strings. The first is with a character array and the second is with a string pointer.
A character array is declared in the same way as a normal array.
char ca[10];You must set the value of each individual element of the array to the character you want and you must make the last character a 0. Remember to use %s when printing the string.
char ca[10];String pointers are declared as a pointer to a char.
ca[0] = 'H';
ca[1] = 'e';
ca[2] = 'l';
ca[3] = 'l';
ca[4] = 'o';
ca[5] = 0;
printf("%s",ca);
char *sp;When you assign a value to the string pointer it will automatically put the 0 in for you unlike character arrays.
char *sp;You can read a string into only a character array using scanf and not a string pointer. If you want to read into a string pointer then you must make it point to a character array.
sp = "Hello";
printf("%s",sp);
char ca[10],*sp;String Handling Functions:
scanf("%s",ca);
sp = ca;
scanf("%s",sp);
The strings.h header file has some useful functions for working with strings. Here are some of the functions you will use most often:
strcpy(destination,source)
You can't just use string1 = string2 in C. You have to use the strcpy function to copy one string to another. strcpy copies the source string to the destination string.
s1 = "abc";strcat(destination,source)
s2 = "xyz";
strcpy(s1,s2); // s1 = "xyz"
Joins the destination and source strings and puts the joined string into the destination string.
s1 = "abc";strcmp(first,second)
s2 = "xyz";
strcat(s1,s2); // s1 = "abcxyz"
Compares the first and second strings. If the first string is greater than the second one then a number higher than 0 is returned. If the first string is less than the second then a number lower than 0 is returned. If the strings are equal then 0 is returned.
s1 = "abc";strlen(string)
s2 = "abc";
i = strcmp(s1,s2); // i = 0
Returns the amount of characters in a string.
s = "abcde";
i = strlen(s); // i = 5
PREVIOUS NEXT
0 Comments:
Post a Comment
Please Leave You Queries Here And Contact Me If You Need Help