如何在C++中更改字符串中的字符
How to change a char in a string in C++
我试图解决这个问题,但我认为我没有正确处理字符串部分。问题是给定一个字符串(比方说"abc"),写出这个字符串的所有大小写组合。
我的方法是修改二进制计数器方法。
下面是我的实现:
#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"
,其中字符数组存储在常量中?
您可以执行类似的操作
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);
}
以使代码更具可读性。
您需要包含string
标头
#include <string>
除此之外,它似乎在VS2013 中运行良好
我认为在计算可能输出的数量时,您过于复杂了;也许这会有所帮助:
for(i=0;i<input.length();i++)
{
for(j=0;j<input.length();j++)
{
printString(input);
changeCase(input[j]);
}
printString(input);
changeCase(input[i]);
}
相关文章:
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 尝试将字符串/字符转换为整数会产生意外结果
- 为什么没有访问所有字符串字符?
- 将子字符串字符从字符串值转换为 int,然后将其分配给 int 变量
- 如何将字符串字符与结构数组进行比较?
- 将单个字符串/字符输入串行监视器
- 读取字符串字符时出错 - 对于数组中的字符串值
- C++ C 样式字符串/字符数组的大小 - 优化
- 读取字符串字符时出错
- C++ 使用 Strtok 读取字符串字符时出错
- 如何将 int 数组的 1 个元素转换为字符串/字符
- 在另一个字符串中逐个复制字符串字符
- 将字符串字符映射到矢量
- MBED RTOS将Float转换为字符串/字符阵列
- 如何使用字符串字符数组中的 ++ 运算符访问下一个字符串
- 如何比较C++中的单个字符串字符?
- 内部字符串/字符如何在 int 和 float 中存储
- 将十六进制转换为可打印的字符串/字符
- wcscpy_s后读取字符串字符时出错
- 检查字符串字符和长度