要從一個輸入的字串中判斷是否有“+”or“-”or“*or”/“,
我這么寫的
string str
if(str.find('+') != string.npos)
{
position=str.find('+');
......
}
else if(str.find('-') != string.npos)
{
position=str.find('-');
......
}
else if(str.find('/') != string.npos)
{
position=str.find('/');
......
}
else if(str.find('*') != string.npos)
{
position=str.find('*');
......
}
就是要一個符號的position,怎么簡化一下
不是決議運算式,不用猜
uj5u.com熱心網友回復:
#include <iostream>僅供參考~
#include <string>
using namespace std;
int main(void) {
string str, target = "+-*/";
auto positoin = string::npos;
for (char c : target) {
if ((positoin = str.find(c)) != string::npos)
break;
}
return 0;
}
uj5u.com熱心網友回復:
if( ( (position = str.find('+') )!=string::npos) ||
( (position = str.find('-') )!=string::npos) ||
( (position = str.find('*') )!=string::npos) ||
( (position = str.find('/') )!=string::npos)
){
//other code...
}省了再查詢一次的步驟,同時縮到一個if里執行了
uj5u.com熱心網友回復:
因為你這個是or的關系,可以考慮用hash, 這樣只需要遍歷str一次就能得出結論了
char str_hash[256] = {0};
str_hash[(unsigned char)'+'] = 1;
str_hash[(unsigned char)'-'] = 1;
str_hash[(unsigned char)'*'] = 1;
str_hash[(unsigned char)'/'] = 1;
string str="abcd-+sdfajjj";
int get_operator_pos(string &str)
{
for(int i = 0; i < str.size(); i++)
{
char ch = str[i];
if(str_hash[(unsigned char) ch] != 0)
return i;
}
}
uj5u.com熱心網友回復:
用正則運算式,你這樣判斷有很嚴重缺點,如果條件多個就會多次遍歷,嚴重影響效率uj5u.com熱心網友回復:
linux的find原始碼是跳著跳著判斷的,效率高了一倍多,很厲害。uj5u.com熱心網友回復:
直接寫不除錯
int 獲取位置(string str,char a)
{
if(str.find(a) != string.npos)
return position=str.find('+');
}
uj5u.com熱心網友回復:
不除錯就別發出來position是什么東西?
uj5u.com熱心網友回復:
bool findop(const string& str, int ch)
{
char ch = 0;
sscanf(str.c_str(), "%*[^-+*/]%c", &ch);
return !!ch;
}
uj5u.com熱心網友回復:
bool findop(const string& str)
{
char ch = 0;
sscanf(str.c_str(), "%*[^-+*/]%c", &ch);
return !!ch;
}
糾正 第二個引數是多余的
uj5u.com熱心網友回復:
有一種優化叫“表驅動“uj5u.com熱心網友回復:
謝謝大家 學到很多新方法轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/98885.html
標籤:C++ 語言
上一篇:求助大佬這個題怎么做
下一篇:關于列印的排版問題
