2017-10-09 179 views
-2

我有一個char數組,我可以根據需要將其轉換爲字符串。給定一個字符串,如何檢查前幾個字符是否是另一個字符串? C++

該字符串可以是一整個句子,但我只關心字符串的前6個字符,因爲它們是我的程序的命令行爲(添加/刪除/刪除等)。

我想知道,我會怎麼做呢?要麼檢查前幾個字符,要麼只是評估字符或字符串數​​組中的第一個單詞。

+2

您可能想要查看substr()方法以提取前6個字符,或者如果要在原地進行比較,則可以使用compare()方法。 – Steve

+0

'std :: strncmp'是一個選項 – vu1p3n0x

+0

「*或甚至更好,只是評估第一個單詞*」 - 從字符串創建一個std :: istreamstream',使用'operator >>'提取第一個單詞它碰巧是)到一個'std :: string'中,然後使用'operator =='根據需要測試它的值 –

回答

0

例如,要比較S1 == S 2(0,10),這意味着字符串S2的前十個字符,使用SUBSTR()可以通過工作,就像這樣:

s1 == s2.substr(0, 10); 

其中,s2.substr(POS,n)的意味着連續ñ字符串S2POS個位置開始。

另一個funtion也GOOT使用:

s1.compare(pos1, n1, s2); 

menas:比較N1字符字符串從s1的POS1位置開始,字符串2.您可以檢出打開了該功能及其超載等五大funtions 。

0

要做到這一點,只需使用std::strncmp()。例如:

bool first_n_equal(const char *lhs, const char *rhs, size_t n) { 
    return (std::strncmp(lhs, rhs, n) == 0); 
} 

注意strncmp返回0,如果兩個字符串相等,只會最多比較n字符。要選擇n,您可以硬編碼6,或循環查看字符串,並檢查第一個單詞結束的位置。例如,

size_t size_of_first_word(const char *str) { 
    size_t i; 
    for (i = 0; str[i] != ' ' && str[i] != '\0'; i++) {} 
    return i; 
} 

此函數遍歷字符串,直到遇到空格或空終止符(字符串結尾)爲止。然後,實際檢查字符串命令:

size_t input_len = size_of_first_word(input_string); 
size_t command_len = size_of_first_word(command_string); 
size_t check_len = std::min(input_len, command_len); 
bool is_same = first_n_equal(input_string, command_string, check_len); 

我故意做出這種冗長,使其更容易理解,所以你絕對可以使此代碼更小。您也可以使用std::string,但實際上並非必要。

相關問題