/* This program demonstrates c-strings * a c-string is an array of chars. * chars are still integer types. When we store a character in a variable or as an array * element, it stores the equivalent ASCII value of that character, as an integer * So, we can do math with characters, since they are internally numbers. * * This program shows us the 4 main functions for c-string * 1. Finding the length of a string: strlen * 2. Copying strings: strcpy * 3. concatenating strings: strcat * 4. Comparing strings: strcmp * * We also implement strcpy and strcmp ourselves, to understand how they work * * A note on ASCII: * In C++, char is both an integer type and a character type. This is because * C++ stores a char as an integer but interprets it as a character when it is * printed. * Since the days of telegraph, we have had the American Standard Code for * Information Interchange (ASCII), which assigns a numeric (integer) value for * every character that can be typed in. We have a numeric equivalent for every * uppercase letter, lowercase letter, numeral character, special character, * whitespace, control characters, etc. * When we store a character in a char variable (or a spot in a C-String), we * actually store the ASCII value of the character. */ #include #include using namespace std; void stringCopy(char st1[], char st2[]); int stringCompare (char st1[], char st2[]); int main() { char str[200]; char copy[200]; cout<<"Enter a string: "; cin.getline(str, 200, '#'); cout<<"Enter another string: "; cin.getline(copy, 200); cout<<"You entered: "< Patrick is "first" P < S * Spongebob , patirck -> Spongebob is "first", S < p * Spongebob, 4atrick -> 4atrick is "first", numeral < letters * Spongebob, Sqiudward -> Spongebob is "first" S==S, p Square is first, first 3 letters are the same, a < i * Squid, Squidward -> Squid is "first", all letters matched until "Squid" ran out of letters * Squid Squid -> strings are equal */ cout<<"Demonstrating strcmp for string comparison:\n"; char str2[100]; cout<<"Enter a string to compare: "; cin.getline(str2,100); int diff = strcmp(str, str2); if (diff < 0) cout< 0) cout< 0) cout< uppercase characters -> lowercase characters * This is because we compare the ASCII values. * strcmp(string1, string2) * string comparison moves through both strings one character at a time, * and subtracts the ASCII value of the character of the second string * from the character of the first string. * The moment it sees a non-zero result on the subtraction, it returns that * So, strcmp returns * value < 0 if the first string occurs before the second string * value > 0 if the second string occurs before the first string * 0 if the strings are exactly equal (including case, spaces, etc.) */ int stringCompare(char st1[], char st2[]) { int diff = 0; int i=0; int len1 = strlen(st1), len2 = strlen(st2); while( i< len1 && i