// 036.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
void DeleteOneStr(char *pBuffer, char str)
{
if (NULL == pBuffer || str == '\0')
{
return;
}
//
// while(*pBuffer != '\0')
// {
// if (*pBuffer == str)
// {
// //*pBuffer = '';
// *pBuffer = *(pBuffer+1);
// }
// pBuffer++;
// }
int i=0;
for (i=0; pBuffer[i] != '\0'; i++)
{
if (pBuffer[i] == str)
{
for (int j=i; pBuffer[j]!= '\0'; j++)
{
pBuffer[j] = pBuffer[j+1];//删除一个字符相当于把这个字符后的每一个字符向左边移动一位
}
}
}
}
void DeleteStr(char *pBuffer, const char *pStr)
{
if (NULL == pBuffer || NULL == pStr)
{
return;
}
const int MAX_SIZE = 256;
int timesOfBufferCh[MAX_SIZE];//pBuffer每个字符串出现的次数
int timesOfStrCh[MAX_SIZE];//pStr每个字符串出现的个数
int i=0;
int j=0;
for (i=0; i<MAX_SIZE; i++)
{
timesOfBufferCh[i] = 0;
timesOfStrCh[i] = 0;
}
char *pBufferBegin = pBuffer;
const char *pStrBegin = pStr;
while(*pBufferBegin != '\0')
{
++timesOfBufferCh[*pBufferBegin];
pBufferBegin++;
}
while(*pStrBegin != '\0')
{
++timesOfStrCh[*pStrBegin];
pStrBegin++;
}
pBufferBegin = pBuffer;
while(*pBufferBegin != '\0')
{
if(timesOfBufferCh[*pBufferBegin] != 0 && timesOfStrCh[*pBufferBegin] != 0)
{
DeleteOneStr(pBuffer, *pBufferBegin);
pBufferBegin = pBuffer;
continue;
}
pBufferBegin++;
}
}
void Delete(char *pSrc, const char *pDeleteStr)
{
if (NULL == pSrc || NULL == pDeleteStr)
{
return;
}
const int MAX_SIZE = 256;
int timesOfCh[MAX_SIZE];
int i=0;
for (i=0; i<MAX_SIZE; i++)
{
timesOfCh[i] = 0;
}
while(*pDeleteStr != '\0')
{
timesOfCh[*pDeleteStr] = 1;//删除字符里存在的字符其次数记录为1
pDeleteStr++;
}
//每次pFast跳过删除的字符。
//当不是需要删除的字符时候,把pFast指向的字符赋值给pSlow。同时pFast和pSlow指向下一个字符。当是需要删除的字符时,pFast跳过需要删除的字符
char *pSlow = pSrc;
char *pFast = pSrc;
while(*pFast != '\0')
{
if (0 == timesOfCh[*pFast])//无需删除
{
*pSlow = *pFast;
pFast++;
pSlow++;
}
else if (1 == timesOfCh[*pFast])
{
pFast++;
}
}
*pSlow = '\0';//最后添加结束符号
}
//题目:输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。
int main(int argc, char* argv[])
{
char pBuffer[] = "They are students.";
char pStr[] = "aeiou";
/*****思路1
DeleteStr(pBuffer, pStr);
printf("%s",pBuffer);
**********/
//思路2
Delete(pBuffer, pStr);
printf("%s",pBuffer);
return 0;
}
036-字符串
最新推荐文章于 2021-05-10 11:17:55 发布