Length of a C-Style String
You can use the
strlen(str)function to find the length of a null-terminated C-style string.
Write a program that uses a function to calculate the length of a null-terminated C-style string (without using the strlen function) by iterating until the null character is reached.
Answer
#include <iostream>
// Function to calculate the length of a C-style string
int stringLength(char *str) {
int length = 0;
while (str[length] != '\0') {
++length;
}
return length;
}
int main() {
char cString[] = "Hello, World!";
// Call the custom function to calculate the length
int length = stringLength(cString);
// Output the length of the string
std::cout << "Length of the string: " << length << std::endl;
}
The length is gotten by iterating through characters from the starting point passed into
stringLengthand incrementing the length until the null-character ('\0') is reached.