将字符串的第一个字节递增1

时间:2013-11-05 05:23:50

标签: c string pointers

我有一个main计划:

int main() {
    char *str = "hello";
    printf("%s\n", str);
    /* Shift first byte 1 to get "iello" */

    /* Have tried
    str[0] >>= 8; */
    printf("%s\n", str);
    return 0;
}

基本上将字符串的第一个字节向上移动一个字节,从hello转换为ielloHello转换为Iello

3 个答案:

答案 0 :(得分:5)

您无法修改字符串文字,请将其更改为:

char str[] = "hello";   //not string literal
printf("%s\n", str);
str[0]++;              //add 1 to the first element
printf("%s\n", str);

答案 1 :(得分:3)

char *str = "hello";是一个不可修改的字符串文字。

用于各种基数的ASCII和i的表示形式为:

  dec  char bin         hex  oct
  104.    h 0110 1000  0x68 0150
  105.    i 0110 1001  0x69 0151

正如你所看到的,第1位从h翻转到i,所以如果你想通过位操作改变它,一种方法是:

#include <stdio.h>

int main(void) 
{
    char str[] = "hello";

    printf("%s\n", str);
    str[0] |= 0x01;
    printf("%s\n", str);

    return 0;
}

使用增量使用:

++str[0];

或:

 char *p = str;
 ++*p;

同样,增量和位处理都是大写的。


如果使用ASCII集,还有其他不错的属性。举个例子:

dec  char bin         hex  oct
 65. A    0100 0001  0x41   101o
 66. B    0100 0010  0x42   102o
 67. C    0100 0011  0x43   103o
 68. D    0100 0100  0x44   104o
            |
            +--- flip bit 5 to switch between upper and lower case.
                 This goes for all alpha characters in the ASCII set.
 97. a    0110 0001  0x61   141o
 98. b    0110 0010  0x62   142o
 99. c    0110 0011  0x63   143o
100. d    0110 0100  0x64   144o

因此:

char str[] = "hello";

str[0] ^= 0x20;
printf("%s\n", str);    /* Print Hello */

str[0] ^= 0x20;
printf("%s\n", str);    /* Print hello */

另一个更频繁使用的,例如也是相同的。 EBCDIC,是数字的属性。它们的排序距离为0,并且在连续范围内,所以:

char num[] = "3254";
int n1 = num[0] - '0'; /* Converts char '3' to number 3 */
int n2 = num[1] - '0'; /* Converts char '2' to number 2 */
etc.

在将十六进制值的字符串表示转换为数字时,您可以将此扩展为ASCII,因为字母字符也按顺序排列:

unsigned hex_val(char c)
{
    if (c >= '0' && c <= '9')
        return c - '0';
    if (c >= 'a' && c <= 'f')
        return c - 'a' + 10;
    if (c >= 'A' && c <= 'F')
        return c - 'A' + 10;
    return ~0;
}

行。我最好还是停在那里......

答案 2 :(得分:2)

做类似的事情:

#include <stdio.h>
#include <ctype.h>

int main() {
char str[] = "hello";
printf("%s\n", str);

//str[0]=str[0]+1;

// to get uppercase letter include ctype.h header

str[0] = toupper(str[0] + 1);

printf("%s\n", str);
return 0;
}