问题:
函数将字符串中的字符'*'移到串的前部分,前面的非'*'字符后移,但不能改变非'*'
分析:
由于问题的特殊性,我们可以直接将字符往后移,那么前面的位置全部用'*'填充,具体代码如下:
#include <iostream>
#include <cstdio>
using namespace std;
/*
* 这个方法将'*'往前移
*/
int change1(char *str)
{
int i, j = strlen(str) - 1;
for (i = j; j >= 0; j--)
{
if (str[i] != '*') //i用来记录最右边的'*'的位置
{
i--;
}
else if (str[j] != '*') //如果i当前有'*',那么找到一个字母,并且将字母替换'*'
{
str[i] = str[j];
str[j] = '*';
i--;
}
}
return i + 1;
}
/*
* 这个方式是将'*'号往后移
*/
int change2(char *str)
{
int i, j, len = strlen(str) - 1;
for(j = 0, i = 0; j <= len; j++)
{
if(str[i] != '*')
{
i++;
}
else
if(str[j] != '*')
{
str[i] = str[j];
str[j] = '*';
i++;
}
}
return len - i + 1;
}
/*
* 这个方法将'*'往前移
* 方法比方法一更简单,而且更好理解
*/
int change3(char * str)
{
int i, j = strlen(str) - 1;
for(i = j; j>=0; j--)
{
if(str[j] != '*')
str[i--] = str[j];
}
for(int t = 0; t <= i; t++)
str[t] = '*';
return i + 1;
}
int main(int argc, char* argv[])
{
// char str[] = "ab**cd**e*12";
char str[] = "*******";
printf("str1=%s\n", str);
printf("str2=%s, count=%d", str, change3(str));
}
总结:
有时问题,灵机一动,可能会想到一个更好的方法。