用数组应该是可以的,只是第17和第19行是使用指针的方式访问的,所以把第17行和第19行的*s改为s[i]应该就可以了,测试代码如下:
#include <iostream>
#include <string.h>
using namespace std;
void fun(char *s){ // 使用数组
int i=0;
while(s[i]!=0){
if(s[i]>='A'&&s[i]<='Z'){
s[i]=s[i]+32; // 用数组下标的方式访问数组元素 ,大写转小写
}else if(s[i]>='a'&&s[i]<='z'){
s[i]=s[i]-32; // 用数组下标的方式访问数组元素 ,小写转大写
}
i++;
}
}
void fun2(char *s){ // 使用指针
int i=0;
while(*s!=0){
if(*s>='A'&&*s<='Z'){
*s=*s+32;
}else if(*s>='a'&&*s<='z'){
*s=*s-32;
}
s++;
}
}
int main(void){
char str[100],stemp[100];
cout<<"请输入一个字符串:";
cin>>str;
strcpy(stemp,str);
// cout<<"str="<<str<<endl;
// cout<<"stemp="<<stemp<<endl;
cout<<"使用数组的结果为:"<<endl;
fun(str);
cout<<str<<endl;
cout<<"\n使用指针的结果为:"<<endl;
fun2(stemp);
cout<<stemp<<endl;
return 0;
}
第一图第17行与第19行,*s始终指向的是字符串首字符,改为:*(s+i) = *(s+i) +32 ; *(s+i) = *(s+i) - 32 ; 即可。