2013-11-20 38 views
0

我試圖解決這個問題,但我認爲我沒有在字符串處理部分的權利。 問題給出一個字符串(比方說「abc」)寫出這個字符串的所有大小寫組合。如何在C++中更改字符串中的字符

我的方法是修改二進制計數器方法。

因此,這裏是我的實現:

#include <iostream> 
#include <cmath> 

#define LOWER_CASE_DIFF 'a'-'A' 

using namespace std; 

void changeSeq(string &in, int amount) { 
    int i = 0; 
    while (i < amount && (int)in[i] < 'a') { 
     in[i] += LOWER_CASE_DIFF; 
     i++; 
    } 
    if (i < amount) { 
     in[i] -= LOWER_CASE_DIFF; 
    } 
    cout << in << endl; 
} 
int main() { 
    string input = "abc"; 
    int diff = 'a' - 'A'; //a is always bigger than A in ASCII 
    int comb = (int)pow(2,(float)input.length()); 
    for (int i = 1; i <= comb; i++) { 
     changeSeq(input, i);  
    } 


    return 0; 
} 

我收到此運行時錯誤:

/usr/local/lib/gcc/i686-pc-linux-gnu/4.1.2/../../../../include/c++/4.1.2/bits/basic_string.h:707: typename _Alloc::rebind<_CharT>::other::reference std::basic_string<_CharT, _Traits, _Alloc>::operator[](typename _Alloc::rebind<_CharT>::other::size_type) [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>]: Assertion '__pos < size()' failed. 

Disallowed system call: SYS_kill 

所以,我怎麼能更改一個字符的時間? C中的字符串行爲類似於C中的const char* str = "abc",其中字符數組存儲在常量中?

+1

你可以改變字符串的內容,但我覺得你的問題是與索引 - IE瀏覽器訪問'如果字符串少於6個字符輸入[6]'無效。你有沒有至少調試一下,看看它打破了什麼? –

+1

'(int)pow(2,(float)input.length())'是一個非常糟糕的主意。浮點數不是精確的,所以有可能是'pow(2,3)== 7.99999',因此'(int)pow(2,3)== 7' ... – 2013-11-20 10:58:37

+0

有趣的是,它適用於我:http://ideone.com/VRLPNI – Constantinius

回答

0

您需要包括string

#include <string> 

其他則是,它似乎在VS2013工作正常

1

你可以做這樣的事情

string s = "ABC"; 
    int comb = 1 << s.length(); 
    for (int i = 0; i < comb; ++i) // 0000 0001 0010 ... 1000 
    { 
    for (size_t j = 0; j < s.length(); ++j) 
    { 
     if (i & (1 << j)) 
     { 
     s[j] = tolower(s[j]); 
     } 
     else 
     { 
     s[j] = toupper(s[j]); 
     } 
    } 
    cout << s << endl; 
    } 

很可能是最好包括一個

bool testbit(int value, int bit) 
{ 
    return value & (1 << bit); 
} 

使代碼更具可讀性。

0

我想你是在嘗試計算可能的輸出數時過於複雜的事情;也許這會幫助:

for(i=0;i<input.length();i++) 
{ 
for(j=0;j<input.length();j++) 
{ 
    printString(input); 
    changeCase(input[j]); 
} 
printString(input); 
changeCase(input[i]); 
} 
相關問題