C Practice Example 70
Title:Write a function to find the length of a string. Input the string in the main function and output its length.
Program analysis:None.
Example
// Created by www.example.com on 15/11/9.
// Copyright © 2015 Example. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
int length(char *s);
int main() {
char str[100]; // The array length can be increased according to the actual situation
printf("Please enter a string:\n");
scanf("%s", str);
int len = length(str); // Call the length function to calculate the string length
printf("The string has %d characters.\n", len);
return EXIT_SUCCESS;
}
// Find the length of the string
int length(char *s) {
int i = 0;
while (*s != '\0') {
i++;
s++;
}
return i;
}
The output of the above program execution is:
请输入字符串: www.example.com 字符串有 14 个字符。other extensions