[Legacy Content] This page contains very old information, which might not be valid anymore, they are only kept here for legacy purposes.
if you have any inquiries, feel free to contact me! Click here
Created: Tuesday, 24 September 2013 Written by Ehab Eldeeb
A string is simply "Array of characters"
A Character could be 'a' or 'b' or '1' or '2' or '@' or '#' ..... whatever on your keyboard is a character
Declare an "Array of characters" ... Just like any other array
char x[11];
This is an array of TEN characters (why?)
Every string MUST end with a "\0" which is "NULL" character
So that 11th place is reserved for the NULL
Always make sure that your "word" has a number of characters LESS than the string size by at least one.
Reading a string..
You can read it with scanf just like normal arrays .. just without a for loop
scanf("%s ", x); // Notice: here we wrote x not &x
Printing out a string..
Similarly printf("%s", x);
The only drawback of reading a string with scanf is that it should be one word, because when you press "space" the string is terminated.
Yes .. gets and puts totally replace scanf and printf when dealing with strings
gets(x); // This is totally similar to scanf BUT you can add as many characters as the length of the string could handle ( can handle spaces too! )
puts(x); // Similar to printf("%s", x); ... No difference at all, just easier to write
Strings have special functions to deal with them
You should learn how to write these functions, but you are not obliged to write them all time .. It's just for your knowledge.
int y;
char x[50] = "Ehab Eldeeb is awesome";
char z[50] = "EhabEldeeb.com";
y = strlen(x); // the "y" variable will hold the number of characters placed in string x .. which is 22 in this case :-)
y = strcmp(x,z); // the "y" variable will hold a positive integer or a negative integer or ZERO
positive integer means string z came before string x in alphabetical order
negative integer means string x came before string z in alphabetical order
zero means both strings are identical
strcpy(x,z); // Takes what's in string z (second parameter) and puts it in string x (first parameter)
What was in x will be totally replaced with what's in z
and what's in z will stay the same without any change
strcat(x,z); // strcat stands for "String Concatenate" .. which means paste the 2nd string after the 1st one
That means when we concatenate x with z we get... "Ehab Eldeeb is awesomeEhabEldeeb.com"
Just pasted the 2nd one after the first one
So string x will containt this sentence: "Ehab Eldeeb is awesomeEhabEldeeb.com"
and string z will remain unchanged: "EhabEldeeb.com"
That's all about strings :-)