Is it possible to print out only a certain section of a C-string, without making a separate substring?

后端 未结 3 1586
误落风尘
误落风尘 2020-12-02 16:46

Say I have the following:

char* string = \"Hello, how are you?\";

Is it possible to print out only the last 5 bytes of this string? What ab

3条回答
  •  盖世英雄少女心
    2020-12-02 17:15

    Is it possible to print out only the last 5 bytes of this string?

    Yes, just pass a pointer to the fifth-to-the-last character. You can determine this by string + strlen(string) - 5.

    What about the first 5 bytes only?

    Use a precision specifier: %.5s

    #include 
    #include 
    char* string = "Hello, how are you?";
    
    int main() {
      /* print  at most the first five characters (safe to use on short strings) */
      printf("(%.5s)\n", string);
    
      /* print last five characters (dangerous on short strings) */
      printf("(%s)\n", string + strlen(string) - 5);
    
      int n = 3;
      /* print at most first three characters (safe) */
      printf("(%.*s)\n", n, string);
    
      /* print last three characters (dangerous on short strings) */
      printf("(%s)\n", string + strlen(string) - n);
      return 0;
    }
    

提交回复
热议问题