我试图解决这个问题,但我认为我没有在字符串处理部分的权利。 问题给出一个字符串(比方说“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"
,其中字符数组存储在常量中?
你可以改变字符串的内容,但我觉得你的问题是与索引 - IE浏览器访问'如果字符串少于6个字符输入[6]'无效。你有没有至少调试一下,看看它打破了什么? –
'(int)pow(2,(float)input.length())'是一个非常糟糕的主意。浮点数不是精确的,所以有可能是'pow(2,3)== 7.99999',因此'(int)pow(2,3)== 7' ... – 2013-11-20 10:58:37
有趣的是,它适用于我:http://ideone.com/VRLPNI – Constantinius