c++ - 一个修改c语言字符串的值的小问题
巴扎黑
巴扎黑 2017-04-17 15:04:07
0
4
640

一个修改c语言字符串的值的问题,改变每一个字符,给ASCII码加上一定数值..试了好几次都没成功...

(注:这里的字符串必须要用char * 且事先无法知道长度 最好也不能包含string头文件)

这是自己测试时候的代码:

#include <stdio.h>

int main(int argc, const char * argv[]) {
    // insert code here...
    printf("Hello, World!\n");

    char* a = "1234";
    
    while(*a!='\0'){
    
        //这里修改字符串的字符的值,给每一个字符的ASCII码加上一定数值
        
        printf("%c\n",*a);
        a=a+1;
    }
    
    //希望这个时候变成比如 "3456" 或者 "abcd" 或者这类..
    
    return 0;
    
}

应该算是简单的问题...这里我自我检讨基础不好...

请了解的朋友看看, 谢谢

巴扎黑
巴扎黑

reply all(4)
迷茫
#include <stdio.h>

int main(int argc, const char * argv[]) {
    // insert code here...
    printf("Hello, World!\n");

    char* a = "1234";
    char* p = a;
    while(*p != 'rrreee'){    
        //这里修改字符串的字符的值,给每一个字符的ASCII码加上一定数值        
        printf("%c\n",*p);
        *p += 1;
        p++;
    }
    
    //希望这个时候变成比如 "3456" 或者 "abcd" 或者这类..
    printf("a=%s",a);
    return 0;    
}
伊谢尔伦

C language strings are constants and cannot be modified. Your intention can be achieved through a character array:

char a[] = "1234";
for (int i = 0; i < 4; i++) {
        a[i] += 1;
}
printf("%s\n", a);
伊谢尔伦

char* a = "1234";The content of the string here is stored in the literal constant area and cannot be changed
char a[] = "1234";The string here can be changed on the stack

#include <stdio.h>

int main(int argc, const char * argv[]) {
    // insert code here...
    printf("Hello, World!\n"); // wtf?

    char a[] = "1234";
    char *p = a;
    while(*p!='rrreee'){
        *p += 2;
        printf("%c\n",*p);
        p++;
    }
    return 0;   
}
刘奇

Let me add something too

const char *a = "1234";
is the type of a...

Other @garfileo @Fallenwood said very well

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template