#include using namespace std; /** * This illustrates some basic string functionality and usage of the 4 functions created * in class. */ int main() { // strlen { cout << endl << "strlen\n------\n"; // notice the '\0' 0-byte string terminating character char s[100] = {'h','e','l','l','o','\0'}; // This is how you could print the string character by character, // looping until we see the '\0' cout << "Print string in for loop: "; for (int i=0; s[i] != '\0'; i++) { cout << s[i]; } cout << endl << "Print string using cout : " << s << endl; cout << endl << "Print string length, notice that even " << endl << "though the array is of size 100, the " << endl << "answer is the number of chars before \'\\0\'" << endl << endl; cout << "strlen: " << strlen(s) << endl; } // strcpy { cout << endl << "strcpy\n------\n"; char dest[50]= "hello"; char origin[5 + 1] = "world"; cout << "Before: " << dest << endl; strcpy(dest,origin); cout << "After : " << dest << endl; } // strcat { cout << endl << "strcat\n------\n"; char dest[50]= "hello"; char origin[5 + 1] = "world"; cout << "Before: " << dest << endl; strcat(dest,origin); cout << "After : " << dest << endl; } // strcmp // Please notice all the different ways we create strings here. { cout << endl << "strcmp\n------\n"; cout << "A return of 0 means the strings are equal, \n" << "any other values means they are not." << endl << endl; char s1[50]= "hello"; // initializing using string char s2[50]= {'h','e','l','l','o','\0'}; // initialize using array // they are equivalent! cout << "Compare [" << s1 << "] and [" << s2 << "]: " << strcmp(s1,s2) << endl ; cout << "[Remove the \'\\0\'] from the second string: "; s2[5] = ' '; cout << strcmp(s1,s2) << endl; // Now compare two totally different strings s2[0] = 'w'; s2[1] = 'o'; s2[2] = 'r'; s2[3] = 'l'; s2[4] = 'd'; s2[5] = '\0'; cout << "Compare [" << s1 << "] and [" << s2 << "]: " << strcmp(s1,s2) << endl ; } cout << endl; return 0; }