2011-06-21 51 views
0

我只想知道是否有一種方法可以使循環處於If語句條件?在IF聲明條件內循環

樣品:

if((string.contains(stringlist.hello().value(0),Qt::CaseInsensitive))||(string.contains(stringlist.hello().value(1),Qt::CaseInsensitive))||(string.contains(stringlist.hello().value(2),Qt::CaseInsensitive))) 
{ 
... 
} 

爲:

if 
(
for(int i=0; i < stringlist.hello().size(); i++) 
{ 
string.contains(stringlist.hello().value(i),Qt::CaseInsensitive) 
} 
) 
{ 
... 
} 

的方式招呼()函數檢索來自數據庫的數據的列表。 該程序的目的是檢查一個字符串是否包含來自數據庫的一些關鍵字。

+3

即使這是有效的語法,這將是一個壞主意,因爲它很難閱讀。這就是函數的作用...創建一個函數來執行循環,給它一個有意義的名字,然後把它稱爲'if'的謂詞。 – Nemo

+0

每隔一段時間在空間中投擲會讓閱讀起來更容易 –

+0

tnx建議 –

回答

7

該代碼不會編譯;相反,你可以嘗試來在每一個條件和結果存儲到一個變量決定的條件是否滿足一個解決方案:

bool testCond = false; 
for(int i=0; i < stringlist.hello().size(); i++) 
{ 
    if (string.contains(stringlist.hello().value(i),Qt::CaseInsensitive)) 
    { 
     testCond = true; 
     break; 
    } 
} 
if (testCond) 
{ 
    // code here if any of the conditions in the for loop are true 
} 

我改變了我的代碼,使用布爾的不是int的,因爲它看起來像你正在使用C++。

+0

生病請嘗試此代碼tnx以獲得幫助。 –

+0

tnx你的代碼工作.. XD –

+1

你可能會在第一個if中放一個'break',這樣你就不會浪費時間'testCond = true;' 或者,你可以改變'for 'condition to'!testCond &&我 karadoc