#include <iostream> using namespace std; int fun( char *s) { char* p = s; while (*p != '\0') p++; return (*p - s); } void main() { cout << fun("abc") << endl; }
时间: 2024-04-04 14:29:20 浏览: 41
这段代码与前面的代码功能相同,都是计算字符串 "abc" 的长度,输出结果为 3。但是这段代码的参数类型是 char*,而不是 char[],它们虽然看起来很像,但是实际上有些细微的差别。char[] 表示一个字符数组,它是一个固定长度的数组,在传递给函数时会被自动转换为指向数组首元素的指针,因此使用 char[] 和 char* 是等效的。而 char* 表示一个指向字符的指针,它可以指向任何长度的字符串,包括空字符串。因此,使用 char* 更加灵活,可以适用于不同长度的字符串。
相关问题
#include <iostream> using namespace std; int fun( char s[]) { char* p = s; while (*p != '\0') p++; return (*p - s); } void main() { cout << fun("abc") << endl; }
这段代码的功能是计算字符串 "abc" 的长度,输出结果为 3,因为最后一个字符的 ASCII 码为 '\0',所以返回的值为 *p - s,即 '\0' - 'a' = 0 - 97 = -97。但是这段代码有一个问题,main 函数应该返回 int 类型而不是 void 类型,正确的写法是将 void main 改为 int main。
#include<iostream> #include<cstring> using namespace std; void fun(char *a) { int len=strlen(a); int startIndex = 0; int endIndex=len-1; while(a[startIndex]=='*'&&startIndex<len) {startIndex++;} while (a[endIndex]=='*'&&endIndex>=0) {endIndex--;} int curIndex = startIndex. for(int i=startIndex;i<=endIndex;i++) { if (a[i]!='*') {a[curIndex++]=a[i]; } } for (int i=curIndex;i<=endIndex;i++) { a[i]='*'; } a[endIndex+1]='\0';} int main() { char a[100]; cout <<"请输入一个不包含空格的带*字符串:"<< endl; cin>>a; fun(a); cout <<"处理后的字符串为:"<< endl; cout << a << endl; return 0; }
这是一段 C++ 代码,实现了一个函数 `fun`,它的功能是去掉字符串首尾的星号 `*`,并将其余字符移动到字符串的前面,后面补上星号。程序中还有一个 `main` 函数,调用了 `fun` 函数对用户输入的字符串进行处理。
具体实现方法是,先找到字符串中第一个不是星号的字符位置和最后一个不是星号的字符位置,然后从第一个不是星号的位置开始,将其余字符移动到字符串的前面,最后在字符串的末尾补上星号。
注意,这段代码假设输入的字符串不包含空格,并且字符串的长度不超过 100。如果输入的字符串超过长度限制,程序可能会发生错误。如果输入的字符串中有空格,那么只会读取空格前面的部分作为字符串,空格后面的部分会被忽略。
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)