A串减去B串中的字符,要求不生成新的字符串。
定义两个指针i和j,i用于保存字符,j用于扫描字符。思想可以扩展到在字符串中去掉冗余空格等问题。
void func(char *A, const char *B)
{
int i = 0, j = 0;
set<char> s;
while(B[i] != '\0')
s.insert(B[i++]);
i = 0;
j = 0;
while(true)
{
while(s.find(A[j]) != s.end())
j++;
if(A[j] == '\0')
break;
A[i++] = A[j++];
}
A[i] = '\0';
}
int main()
{
char A[] = "hello";
char B[] = "le";
func(A, B);
cout<<A;
}
下面是删除冗余空格的代码:
void func(char *A)
{
int i = 0, j = 0;
while(A[j] == '_')
j++;
A[i] = A[j++];
while(A[i] != '\0')
{
while(A[j] == '_')
j++;
if(A[j] != '\0')
A[++i] = '_';
A[++i] = A[j++];
}
}
int main()
{
char s[] = "___A___B_C__";
cout<<s<<endl;
func(s);
cout<<s;
}