自己编写一个求字符串长度的函数,代码中不能出现头文件string.h 函数原型可从main函数中得出,函数返回字符串s的长度,不包括字符串末尾的'\0' Input 输入为多行。每行为一个字符串s。s的字符总数不超过100个。 Output 输出为多行整数,对应每行输入的字符串长度。
时间: 2024-04-08 18:29:13 浏览: 12
以下是一个求字符串长度的函数,代码中不使用头文件string.h:
```c
#include <stdio.h>
int strLength(char *s) {
int length = 0;
while (*s != '\0') {
length++;
s++;
}
return length;
}
int main() {
char s[101];
while (scanf("%s", s) != EOF) {
int length = strLength(s);
printf("%d\n", length);
}
return 0;
}
```
注意,这个函数假设输入的字符串不包含空格。如果输入可能包含空格,你可以使用`fgets()`函数替代`scanf()`函数来读取字符串。
相关问题
己编写一个求字符串长度的函数,代码中不能出现头文件string.h 函数原型可从main函数中得出,函数返回字符串s的长度,不包括字符串末尾的'\0' Input 输入为多行。每行为一个字符串s。s的字符总数不超过100个。 Output 输出为多行整数,对应每行输入的字符串长度。int main() { int n; char s[101]; while(gets(s) != NULL) printf("%d\n", strlen(s)); return 0; }
如果不能使用头文件`string.h`,我们可以手动编写一个求字符串长度的函数。以下是修改后的代码:
```c
#include <stdio.h>
int myStrlen(char s[]) {
int len = 0;
while (s[len] != '\0') {
len++;
}
return len;
}
int main() {
int n;
char s[101];
while (gets(s) != NULL) {
printf("%d\n", myStrlen(s));
}
return 0;
}
```
在这个代码中,我们定义了一个名为`myStrlen()`的函数,它接受一个字符数组作为参数,并返回字符串的长度。函数通过循环遍历字符数组直到遇到字符串的结尾符`\0`,并在每个循环迭代中递增长度计数器。然后在`main()`函数中,我们调用`myStrlen()`函数来计算字符串长度并输出结果。希望对你有所帮助!
用C++编写一个程序,编写函数将字符串按逆序存放(其中头文件有iostream、stdio.h、string.h、fstream)
好的,下面是用 C++ 编写的程序,实现将字符串按逆序存放的功能(包含头文件 iostream、stdio.h、string.h、fstream):
```c++
#include <iostream>
#include <cstdio>
#include <cstring>
#include <fstream>
using namespace std;
void reverse(char str[]) {
int len = strlen(str);
for(int i = 0; i < len / 2; i++) {
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
}
int main() {
char str[100];
cout << "请输入字符串:";
scanf("%s", str);
reverse(str);
cout << "逆序后的字符串为:" << str << endl;
ofstream out("output.txt");
out << str;
out.close();
return 0;
}
```
在上面的程序中,我们同样编写了一个 `reverse` 函数用于将传入的字符串按逆序存放。在 `main` 函数中,我们使用 `scanf` 函数获取用户输入的字符串,调用 `reverse` 函数进行逆序操作,并将结果输出到屏幕上。同时我们使用 `ofstream` 类型的对象 `out` 将逆序后的字符串输出到文件 `output.txt` 中,最后关闭文件。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)