how to access parts of string in c

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • adi108
    New Member
    • May 2007
    • 1

    how to access parts of string in c

    hi

    how does one access parts of string in C.

    string comes back like this in Hyperterminal

    LITL0 0000
    LITL1 0759
    LITL2 0014
    LITL3 0024

    need to access the numbers
    is there a function in C similar to substr in C++?

    thank you
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    You can use strtok() to seperate the string by spaces and get to the numbers. See more on strtok() here.

    Comment

    • AdrianH
      Recognized Expert Top Contributor
      • Feb 2007
      • 1251

      #3
      Originally posted by adi108
      LITL0 0000
      LITL1 0759
      LITL2 0014
      LITL3 0024

      need to access the numbers
      is there a function in C similar to substr in C++?
      You can use scanf() or sscanf() but you need to take some pecautions when using them. I usually use a %n to ensure that that point has been gotten to in the parse.

      Code:
      int position = 0; // must be initilised
      scanf("LITL%*[0-9] %d%n", &number, &position);
      // check that position is not 0.
      FYI, be careful about parsing numbers starting with 0. C/C++ libraries may parse them as octal (base 8) instead of decimal (base 10). You may wish to strip the leading zeros prior to using a C/C++ library function.

      If you are still having problems, let us know.


      Adrian

      Comment

      Working...