编写函数,将一个字符串 str 中指定的字符 ch 删去(包括重复出现的字符),并编写主函 数进行调用测试。
函数原型: void delchar(char *str,char ch);。
输入: 占二行。
第 1 行,输入任意字符串(注:输入的字符串长度不会超过 80)
第 2 行,输入一个字符
输出: 占一行
样例输入: x=-3,456,789; y=1,113,458 ,
样例输出: x=-3456789; y=113458
代码
# include<iostream>
# include<cstring>
# include<string>
# include<fstream>
using namespace std;
void delchar(char *str, char ch){
int n=0;
int i;
for(i=0; str[i]!='\0'; i++){
if(str[i]==ch){
n++;
continue;
}
str[i-n]=str[i];
}
str[i-n]='\0';
}
int main(){
char * str = new char[100];
cin.getline(str, 100);
// cin >> str;
char v;
cin >> v;
delchar(str, v);
// str += 5;
cout << str;
}
数组指针
在使用 char* name定义字符串时,应加上长度限制,如char*str=new char[80];
其中name指向第一个元素的地址,所以如下*a可以输出首元素,而*(a+6)可以输出第七个元素,未定义时为0,当然,上面程序中的str也是一个数组,所以我们可以用str[n]进行处理
同样在字符串char*中,如果想删掉前面的几个字符,只需要 name+=n;即可,即将首指针向后移几位
# include<iostream>
using namespace std;
int main(){
int a[10]={5, 7, 4, 6};
cout << *a << endl;
cout << *(a+6) << endl;
a[6] = 100;
cout << *(a+6) << endl;
}
/*
5
0
100
*/
指针传参
当我想将字符串前面截掉一部分,我可以令str+=5,这个式子写在函数内与函数外有什么区别呢?
运行如下代码可以看出,我们在函数内部改变了str的指向,并可以输出截取后的部分,但在函数外再次输出时,却没有变化
因为:通常情况下,c++是传值调用,它是单向的,只能从实参到形参。形参实质上市实参的一种拷贝,所以传递时不会改变外部实参的值
所以str指向的位置只能在本层及以下发生改变
# include<iostream>
# include<cstring>
# include<string>
# include<fstream>
using namespace std;
void delchar(char *str, char ch){
int n=0;
int i;
for(i=0; str[i]!='\0'; i++){
if(str[i]==ch){
n++;
continue;
}
str[i-n]=str[i];
}
str[i-n]='\0';
cout << str << endl;
str += 5;
cout << str << endl;
}
int main(){
char * str = new char[100];
cin.getline(str, 100);
// cin >> str;
char v;
cin >> v;
cout << str << endl;
str += 5;
cout << str;
}
/*
x=-3456789; y=1113458
56789; y=1113458
x=-3456789; y=1113458
56789; y=1113458
*/
当我们确实想在函数内实现截取,只能曲线救国,不改变str,而费尽的改变这一串字符串的值,比如使用Memcpy函数
比如改为如下,就是建立一个new_s,将目标串写入new_s,再赋给str的相应位置
memcpy函数,将第二个参数的数组赋给第一个参数的位置,第三个参数为赋值的字节数(字符串结尾为'\0',所以+1)
void delchar(char *str, char ch){
int n=0;
int i;
for(i=0; str[i]!='\0'; i++){
if(str[i]==ch){
n++;
continue;
}
str[i-n]=str[i];
}
str[i-n]='\0';
// cout << str << endl;
// str += 5;
// cout << str << endl;
char * new_s = new char[100];
int k=0;
int j;
for(j=5; str[j]!='\0'; j++){
new_s[k++] = str[j];
}
cout << new_s << endl;
memcpy(str, new_s, strlen(new_s)+1);
}
字符串的输入和遍历
字符串输入有几种方式:
getline属于string流,需包含string头文件
cin.getline属于cin流,所以不能用于string类型
而cin遇到空格即结束
代码如下(用了文件读,filen相当于cin):
ifstream file1("vals.txt");
string s;
getline(file1, s);
cout << s << endl;
ifstream file2("vals.txt");
char* s2 = new char[100];
file2.getline(s2, 100);
cout << s2 << endl;
ifstream file3("vals.txt");
char* s3 = new char[100];
file3 >> s3;
cout << s3 << endl;
int len=0;
for(; s2[len]!='\0'; len++){
}
cout << len << " " << strlen(s2) << " " << sizeof(s2) << " " << s.size() << endl;
/*
5 6 9 10 7 -1
5 6 9 10 7 -1
5
13 13 8 13
*/
对于字符串长度的计算,可以用strlen()来计算,但要引用头文件 cstring
也可根据'\0'为最后一个的性质计算
string类型可以采用s.size()函数
但要注意 sizeof返回括号内类型的长度(即指针类型的长度两字节)