Thread: strlen with escape codes

  1. #1
    Registered User
    Join Date
    Apr 2019
    Posts
    662

    strlen with escape codes

    having got my head around arrays (for the next 4 seconds till i go thick again) i am wondering about the return value from strlen

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
        char mystring[40] = "hello";
    
        printf("the length of \"my string\" is %lu\n", strlen(mystring));
    
        return 0;
    }
    this returns 5 as one would expect (5 letters but doesn't count the "\0" character).

    however if i do this:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
        char mystring[40] = "\e[196;5;196m\e[38;5;196mhello\e[0m";
    
        printf("the length of \"my string\" is %lu\n", strlen(mystring));
    
        return 0;
    }
    i count 35 characters but lenstr returns 32. if its ignoring the \e parts i make the count 29 so it cant be that. what has happened to the "missing" 3 characters and when deciding on the length of an array to hold these escape codes and message what do i declare the array length as 36 or 33 including the null.

    many thanks
    coop

  2. #2
    Registered User
    Join Date
    Feb 2019
    Posts
    639
    "\e[192;5;196m" (12 chars)
    "\e[38;5;196m" (11 chars)
    "hello" (5 chars)
    "\e[0m" (4 chars)

    12+11+5+4 = 32

    PS: "\e" is a GCC extension, use "\033" or "\x1b" for portability

  3. #3
    Registered User
    Join Date
    Apr 2019
    Posts
    662
    does it not count the "" then??? thanks for the \033 tip

  4. #4
    Registered User
    Join Date
    Feb 2019
    Posts
    639
    Quote Originally Posted by cooper1200 View Post
    does it not count the "" then??? thanks for the \033 tip
    Ask yourself: How a string, in C, is defined and what is the purpose of strlen()?

  5. #5
    Registered User
    Join Date
    Apr 2019
    Posts
    662
    bother it didnt print the \ that was supposed to be " \ " with no spaces sorry

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 7
    Last Post: 07-31-2017, 10:14 AM
  2. Validate area codes within a list of area codes
    By Staja24 in forum C Programming
    Replies: 9
    Last Post: 05-06-2015, 09:28 PM
  3. Escape Codes
    By renurv in forum C++ Programming
    Replies: 2
    Last Post: 01-01-2006, 02:01 PM
  4. Printer Escape Codes for Epson stylus color 460?
    By DanTheMan in forum C Programming
    Replies: 3
    Last Post: 02-14-2002, 10:30 PM
  5. converting scan codes to ascii codes
    By stupid_mutt in forum C Programming
    Replies: 11
    Last Post: 01-25-2002, 04:06 PM

Tags for this Thread