C++ 移动一串字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6171946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shifting a string of characters?
提问by Christian
I'm writing a program that solves Caesar ciphers in C++. It takes a string of the alphabet and shifts it to the left each loop: "abc....yz" --> "bcd.....yza". The problem is after another loop it goes: "bcd.....yza" --> "cde.....yzaa".
我正在编写一个用 C++ 解决凯撒密码的程序。它需要一个字母字符串并将其向左移动每个循环:"abc....yz" --> "bcd.....yza"。问题是在另一个循环之后:“bcd.....yza”-->“cde.....yzaa”。
char temp; // holds the first character of string
string letters = "abcdefghijklmnopqrstuvwxyz";
while (true)
{
temp = letters[0];
for (int i = 0; i < 26; i++)
{
if (i == 25)
{
letters += temp;
}
letters[i] = letters[i + 1];
cout << letters[i];
}
cin.get();
}
Copy and paste that code and you'll see what I'm talking about. How do I fix this mysterious problem?
复制并粘贴该代码,您就会明白我在说什么。我该如何解决这个神秘的问题?
回答by MSalters
If I'm not mistaken, your loop does precisely the same as the following code:
如果我没记错的话,您的循环与以下代码完全相同:
letters = letters.substr(1,25) + letters.substr(0,1);
// [skip 1, take 25] + [first char goes last]
回答by Nemo
I think you need letters to be 27 characters, not 26, and instead of letters += temp
(which grows the string every time), use letters[26] = temp[0]
.
我认为您需要字母为 27 个字符,而不是 26 个字符,而不是letters += temp
(每次都会增加字符串),使用letters[26] = temp[0]
.
...at which point you can just ditch temp
entirely:
...此时你可以temp
完全放弃:
string letters = "abcdefghijklmnopqrstuvwxyz.";
while (true)
{
letters[26] = letters[0];
for (int i = 0; i < 26; i++)
{
letters[i] = letters[i + 1];
cout << letters[i];
}
cin.get();
}
[edit]
[编辑]
Although the more natural way to handle this is to use arithmetic on the characters themselves. The expression 'a' + ((c - 'a' + n) % 26)
will shift a char c
by n
places Caesar-style.
尽管处理这个问题的更自然的方法是对字符本身使用算术。表达式'a' + ((c - 'a' + n) % 26)
将转向一个烧焦c
的n
地方撒风格。
回答by yasouser
You can achieve this easily using valarray< char >::cshift(n)
(cyclical shift) method.
您可以使用valarray< char >::cshift(n)
(循环移位)方法轻松实现这一点。