英文:
C how to add value to char and limit it so its will give only small letter ('z' + 2 = 'b')
问题
I need to decode a string in c.
each char in the string I add him the value: 2^pos and then get the wanted letter.
but if I do 'z' + 2 its not going to give me a small letter. ( i will get a special char "|")
i thought about doing something like that:
(
value = 2^pos)
if (*(arr + k) >= 'a' && *(arr + k) <= 'z')
{
if (pos == 0)
{
value = 1;
}
if ('z' - (*(arr + k)) <= value)
{
*(arr + k) = 'a' + (value - ('z' - *(arr + k)));
}
else
{
*(arr + k) += value;
}
pos++;
}
I also understand that there is a trick with %26 but i cant find the logic of it before doing it.
英文:
I need to decode a string in c.
each char in the string I add him the value: 2^pos and then get the wanted letter.
but if I do 'z' + 2 its not going to give me a small letter. ( i will get a special char "|")
i thought about doing something like that:
(
value = 2^pos)
if (*(arr + k) >= 'a' && *(arr + k) <= 'z')
{
if (pos == 0)
{
value = 1;
}
if ('z' - (*(arr + k)) <= value)
{
*(arr + k) = 'a' + (value - ('z' - *(arr + k)));
}
else
{
*(arr + k) += value;
}
pos++;
}
I also understand that there is a trick with %26 but i cant find the logic of it before doing it.
答案1
得分: 1
a..=z有26个字符,所以你可以获取字符并减去'a'或'A'或其他。你可以使用该值找到模26,将该余数添加到'a'或'A'上将遵循循环。这是示例代码:
for (int j = 0; j <= 26+10; ++j) {
printf("%c ", (j%26) + 'a');
}
或者
for (int j = 'a'; j <= 'z'+10; ++j) {
printf("%c ", ((j-'a')%26) + 'a');
}
英文:
a..=z is 26 characters, so you can get the character and subtract it by 'a' or 'A' or whatever. You can use that value to find modulo 26 and upon adding that remainder to 'a' or 'A' will follow the cycle. Here's sample code:
for (int j = 0; j <= 26+10; ++j) {
printf("%c ", (j%26) + 'a');
}
or
for (int j = 'a'; j <= 'z'+10; ++j) {
printf("%c ", ((j-'a')%26) + 'a');
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论