字符串处理

#include<iostream>
#include <string.h>
using namespace std;

void replaceback(char  str[],int length)//转换字符串中的某个特殊的字符
{
if (str==NULL || length < 0 )
{
return;
}
int i=0;
int numberb=0;
while (str[i] != '\0')
{
if (str[i] == ' ')
{
++numberb;
}
++i;


}
// 替换 为 %20多两个字节 
int nowlength = length + numberb*2;


if (nowlength < length )
{
return;
}
int pos1=length,pos2=nowlength;
while(pos1 >= 0 && pos2 > pos1)
{
if(str[pos1] == ' ')
{
str[pos2--]='0';
str[pos2--]='2';
str[pos2--]='%';
}
else
{
   str[pos2--]=str[pos1];
}
--pos1;
}
}


void deletel_char(char *str,int length ,char a)//删除字符串中某个特殊的字符
{
if (str==NULL || length < 0 )
{
return;
}
int i=0;
int numberb=0;
while (str[i] != '\0')
{
if (str[i] == a)
{
++numberb;
}
++i;


}
int nowlength = length -numberb;
if (nowlength > length )
{
return;
}
int pos1=0,pos2=0;
while(pos1<=length  && pos2 <= nowlength)
{
if(str[pos1] == a)
{
pos1++;
}
else
{
str[pos2++]=str[pos1++];
}


}


}

//统计只含有字符0或者1的字符串里0和1连续出现的最大次数

void find_max(char*str , int length, int & max_0, int& max_1)//注意值传递和指针传递,引用传递的区别。。。。。。。。。。。。。。。
{
if(str == NULL && length <= 0)
return; 
int temp=0;
int temp_0=0;
int temp_1=0;
while (str[temp] != '\0')//"000010011111100111
{
if(str[temp] == '0')
{
temp_1=0;
temp_0++;
if(temp_0 > max_0)
{
max_0=temp_0;
}
temp++;
//continue;

}
else if (str[temp] == '1')
{
temp_0=0;
temp_1++;
if(temp_1 > max_1)
{
max_1=temp_1;
}
temp++;
//continue;
}
else
{
temp++;
//continue;
}


}


}
int main()
{


//1、char a[10]; a[10]="hello";//一个字符怎么能容纳一个字符串?况且a[10]也是不存在的!
//2、char a[10]; a="hello";//这种情况容易出现,a虽然是指针,但是它已经指向在堆栈中分配的10个字符空间,
//现在这个情况a又指向数据区中的hello常量,这里的指针a出现混乱,不允许!
//还有:不能使用关系运算符“==”来比较两个字符串,只能用strcmp() 函数来处理。
//不能先定义再给它赋值,如char a[10]; a[10]="hello";这样是错误的!
    //char str[30]="I love you";这种赋值的方式是错误的
    //清字符串数组和字符串指针的不同赋值方法
char str[300];
strcpy(str, "I love you, no matter how road ahead diffcult it is ");;
int length = strlen(str);
cout << length << endl;
replaceback(str,length);
cout << str <<endl;


char str1[300];
strcpy(str1, "I love you                                      Thank you ");
int length1 = strlen(str1);
char a =' ';
deletel_char(str1,length1 ,a);
cout << str1 <<endl;


char str2[300];
strcpy(str2, "00001110110000001100110101101001010101011111010");
int length2 = strlen(str1);
int max_0(0),max_1(0);
find_max(str2,length2,max_0,max_1);
cout << "max number of 0: "<< max_0 <<endl;
cout << "max number of 1: "<< max_1 <<endl;
return 0;

}

实验结果:




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值