删除字符串中所有星号c语言,C:从星号不是乘法符号的字符串中删除所有星号...

功能齐全的代码:

#include

#include

using namespace std;

string RemoveAllAstericks(string);

void RemoveSingleAsterick(string&,int);

bool IsDigit(char);

int main()

{

string myString = "hey this is a string * this string is awesome 97 * 3 = 27 * this string is cool";

string newString = RemoveAllAstericks(myString);

cout << "Original: " << myString << "\n";

cout << "Modified: " << newString << endl;

system("pause");

return 0;

}

string RemoveAllAstericks(string s)

{

int len = s.size();

int pos;

for(int i = 0; i < len; i++)

{

if(s[i] != '*')

continue;

pos = i - 1;

char cBefore = s[pos];

while(cBefore == ' ')

{

pos--;

cBefore = s[pos];

}

pos = i + 1;

char cAfter = s[pos];

while(cAfter == ' ')

{

pos++;

cAfter = s[pos];

}

if( IsDigit(cBefore) && IsDigit(cAfter) )

RemoveSingleAsterick(s,i);

}

return s;

}

void RemoveSingleAsterick(string& s,int i)

{

s[i] = ' '; // Replaces * with a space,but you can do whatever you want

}

bool IsDigit(char c)

{

return (c <= 57 && c >= 48);

}

顶级概述:

代码搜索字符串直到遇到*.然后,它查看*之前和之后的第一个非空白字符.如果两个字符都是数字,则代码确定这是乘法运算,并删除星号.否则,它将被忽略.

如果您需要其他详细信息,请参阅此帖子的修订历史记录.

重要笔记:

>您应该认真考虑在字符串上添加边界检查(即,不要尝试访问小于0或大于len的索引

>如果您担心括号,请更改检查空格的条件以检查括号.

>检查每个字符是否都是数字是一个坏主意.至少,它需要两次逻辑检查(参见我的IsDigit()函数). (我的代码检查’*’,这是一个逻辑操作.)然而,发布的一些建议非常糟糕.不要使用正则表达式来检查字符是否为数字.

既然你在问题中提到了效率,而且我没有足够的代表点来评论其他答案:

检查’0”1”2’…的switch语句意味着每个不是数字的字符必须经过10次逻辑操作.请充分尊重,因为字符映射到整数,只需检查边界(字符< ='9'&& char> =’0′)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值