The simplest way of printing a portion of a char[] in C

后端 未结 5 747
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 13:39

Let\'s say I have a char* str = \"0123456789\" and I want to cut the first and the last three letters and print just the middle, what is the simplest, and safes

5条回答
  •  隐瞒了意图╮
    2020-12-13 13:58

    If you don't mind modifying the data, you could just do some pointer arithmetic. This is assuming that str is a char pointer and not an array:

    char string[] = "0123456789";
    char *str = string;
    
    str += 3; // "removes" the first 3 items
    str[4] = '\0'; // sets the 5th item to NULL, effectively truncating the string
    
    printf(str); // prints "3456"
    

提交回复
热议问题