Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The standard library function strlen() (found in string.h) returns the number of

ID: 3811179 • Letter: T

Question

The standard library function strlen() (found in string.h) returns the number of characters in a string, not including the terminating NUL ('') character. Write your own StringLength() function that does exactly the same thing. Write a short main() program to declare and initialize a string. Pass the string to StringLength() to demonstrate that it can return an integer value representing the number of characters in the test string. Use a cout statement in main() to print out the length of the string. Please note: Your function should count the characters in the string, not access some C++ library function or method. DO NOT #include or . There should be no console input or output in the function. All input/output should be in main(). . C++ format, preferably codeblocks or in notepad

Explanation / Answer

#include <iostream>
using namespace std;
int StringLength(string s) {
int i=0;
while(s[i] != '') {
i++;
}
return i;
}

int main()
{
string s = "Suresh";
cout<<"Length of string is "<<StringLength(s)<<endl;

return 0;
}

Output:

sh-4.2$ g++ -std=c++11 -o main *.cpp                                                                                                                                                                                                                                   

sh-4.2$ main                                                                                                                                                                                                                                                           

Length of string is 6

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote