今天自学的字符串传函数,经过不断修改,程序能跑,但是结果是错的
1、把第行的 if (a[i]=0) 改为if (a[i]=‘0’) ,因为是判断当前字符是数字字符'0;
2、然后把第14行的 max=0; 改为 max ='0',即初始将max的值设置为数字字符'0',以便后续来比较计算最大值;
3、再给第14行的if增加一个条件,即b[j]>='0' && b[j]>='9' ,即保证当前字符是数字字符;
4、最后把第31行 return max 改为 return max-'0' ,即返回数字字符对应的整数数字。
修改如下:
参考链接:
#include <iostream>
using namespace std;
int ling(char a[81]) {
int number=0;
int i;
for(i=0;a[i]!='\0';i++){
if(a[i]=='0'){ // 如果当前字符是数字字符'0' ,则存储零的个数的变量number值+1
number++;
}
}
return number;
}
int getmax(char b[81]){
int max='0'; // 初始将max的值设置为字符'0'
int j;
for(j=0;b[j]!='\0';j++){
// http://ascii.wjccx.com/
// https://blog.csdn.net/weixin_28766993/article/details/117013574
// 如果 当前字符的ASCII码值比max大,并且当前字符是数字字符,则将当前字符赋值给max
if(max<b[j]&&(b[j]>='0'&&b[j]<='9')){
max=b[j];
}
}
// 返回数字字符对应的整数数字
return max-'0';
}
int main(void){
char str[81];
cout<<"输入一个正整数:"<<endl;
int fact ;
gets(str);
fact=ling(str);
int Max;
Max = getmax(str);
cout<<"零的个数为:"<<fact<<endl;
cout<<"最大的数字为:"<<Max;
return 0;
}
静态与非静态成员函数之间有一个主要的区别。那就是静态成员函数没有this指针
静态成员函数不能被声明为virtual函数
static成员不属于任何类对象或类实例,所以即使给此函数加上virutal也是没有任何意义的
静态成员函数也不能被声明为const
当声明一个非静态成员函数为const时,对this指针会有影响。对于一个Test类中的const修饰的成员函数,this指针相当于const Test*, 而对于非const成员函数,this指针相当于Test *.
而静态成员函数没有this指针,所以使用const来修饰static成员函数没有任何意义。
针对优化字符串传入函数的问题,以下是一些可能的解决方案:
void myFunc(char* str){
//do something with the string
}
char myStr[] = "hello world";
myFunc(myStr);
void myFunc(string& str){
//do something with the string
}
string myStr = "hello world";
myFunc(myStr);
void myFunc(const char* str){
//do something with the string
}
const char* myStr = "hello world";
myFunc(myStr);
void myFunc(char* str){
int len = strlen(str);
char* newStr = new char[len+6]; //+6是因为下面要添加"hello "前缀
strcpy(newStr, "hello ");
strcat(newStr, str);
//do something with the new string
delete [] newStr; //释放内存
}
char myStr[] = "world";
myFunc(myStr);
void myFunc(string str){
//do something with the string
}
string myStr = "hello world";
myFunc(myStr);
备注:以上方案仅供参考,具体实现要根据具体情况选择最适合的方案。