String initialize and length
Source Code
|
|
Run Output
Code Understanding
This program shows how to store strings, display them, and find their lengths in both C-style and C++ style.
• #include <cstring> → allows use of string-related functions like strlen() for C-style strings.
• char s1[40] = “I love my country”; → creates a C-style string stored in a character array.
• string s2 = “I respect my country”; → creates a C++ style string object.
• cout << s1 << endl; and cout << s2 << endl; → display both strings on separate lines.
• for(i = 0; s1[i] != ‘\0’; i++); → counts the number of characters in s1 until the null character ‘\0’ (end of string).
• cout << “Length of s1 using loop = ” << i << endl; → displays the calculated length of s1 using the loop.
• cout << “Length of s1 using strlen = ” << strlen(s1) << endl; → uses strlen() function to get the length of s1.
• cout << “Length of s2 using length = ” << s2.length() << endl; → uses the length() function to find the length of s2.
• return 0; → ends the program successfully.
Created: 1-Mar-2026 17:40 | Updated: 1-Mar-2026 17:46|
