Results 1 to 4 of 4

Thread: Length of a string displayable in C

  1. #1
    Join Date
    Jan 2009
    Posts
    8

    Length of a string displayable in C

    Does anyone know if there is a function in lib or libX11 which returns the number of characters? (strlen () is not appropriate because it returns the number of bytes)
    Eg "/hame/big/proj$", strlen () returns me 19 while only 15 characters 'to', 'é', 'i', 'O' which are 2octets characters.

    I made a function:
    Code:
    unsigned int StringLength(char *str)
      ( 
        unsigned int nb; 
        char c, flg; 
    
        for (nb = 0, flg = 0; (c = *str) != '\0'; ++str, ++pos) { 
          if (isprint(c) != 0){ // classical character display                                                                                      
            flg = 0; 
            ++nb; 
          ) 
          else if (flg == 0) // if it was the first byte of a 2octets character  
            ++flg; 
          else if (flg == 1) { // 2nd characters display the 2octets 
            ++nb; 
            flg = 0; 
          ) 
        ) 
        if (flg == 1) // If the last character was the 2nd byte character 2octets 
          ++nb; 
        return (nb); 
      )

  2. #2
    Join Date
    May 2008
    Posts
    2,297

    Re: Length of a string displayable in C

    it's utf8:
    Code:
    size_t strlen_utf8 (const char * const s) 
      ( 
         size_t i = 0; 
         size_t j = 0; 
       
         while (s[i])  
         ( 
            if ((s[i] & 0xc0) != 0x80)  
               j++;
             
            i++; 
         ) 
       
         return j; 
      )

  3. #3
    Join Date
    Apr 2008
    Posts
    2,005

    Re: Length of a string displayable in C

    If your string is a wide char (wchar_t-based), the function is wcslen
    If your string is encoded in utf8 mblen should do the trick.

  4. #4
    Join Date
    Jan 2009
    Posts
    8

    Re: Length of a string displayable in C

    What a solution... Wow. Thank you.

Similar Threads

  1. Finding php string length
    By afidelino in forum Software Development
    Replies: 5
    Last Post: 26-02-2010, 07:34 PM
  2. How to reduce URL length
    By Mahish in forum Technology & Internet
    Replies: 4
    Last Post: 05-02-2010, 05:58 AM
  3. Get String Length with Javascript
    By klite in forum Software Development
    Replies: 3
    Last Post: 31-10-2009, 11:39 AM
  4. How to Manipulate String using PHP String Functions
    By ComPaCt in forum Software Development
    Replies: 3
    Last Post: 21-09-2009, 09:07 AM
  5. max length filename
    By John A Grandy in forum Windows Server Help
    Replies: 6
    Last Post: 23-10-2008, 11:00 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,713,502,062.90590 seconds with 16 queries