Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Read String

Read String

Scheduled Pinned Locked Moved C / C++ / MFC
question
13 Posts 10 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A AbhiHcl

    Hi I want to find the number of comma(,) in particular string. Like char* str = "a,b,c,d,e". So how many commas are there in str ? Thanks

    _ Offline
    _ Offline
    _Superman_
    wrote on last edited by
    #2

    Use strchr in a loop.

    char* str = "a,b,c,d,e";
    int count = 0;

    for (;;)
    {
    str = strchr(str, ',');
    if (NULL == str)
    break;

    ++str;
    ++count;
    

    }

    «_Superman_»
    I love work. It gives me something to do between weekends.

    Microsoft MVP (Visual C++)

    Polymorphism in C

    1 Reply Last reply
    0
    • A AbhiHcl

      Hi I want to find the number of comma(,) in particular string. Like char* str = "a,b,c,d,e". So how many commas are there in str ? Thanks

      A Offline
      A Offline
      Aescleal
      wrote on last edited by
      #3

      std::count is your friend. It does exactly what you'd expect it to do from it's name. The only problem you're likely to have is working out where the end of the characters in memory are, but if you're feeling lazy bung the characters in a std::string first:

      std::string s( str );
      std::cout << "There are " << std::count( s.begin(), s.end(), ',' ) << " commas in " << s << std::endl;

      Cheers, Ash

      1 Reply Last reply
      0
      • A AbhiHcl

        Hi I want to find the number of comma(,) in particular string. Like char* str = "a,b,c,d,e". So how many commas are there in str ? Thanks

        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #4

        char c;
        int commas=0;
        while((c=*str++)!=0) if (c==',') commas++;

        :)

        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles] Nil Volentibus Arduum

        Please use <PRE> tags for code snippets, they preserve indentation, and improve readability.

        1 Reply Last reply
        0
        • A AbhiHcl

          Hi I want to find the number of comma(,) in particular string. Like char* str = "a,b,c,d,e". So how many commas are there in str ? Thanks

          C Offline
          C Offline
          Chris Losinger
          wrote on last edited by
          #5
          const char \*p = "a,b,c,de,f,";
          int c = 0;
          for (;\*p;c+=(','==\*p++));
          

          image processing toolkits | batch image processing

          C 1 Reply Last reply
          0
          • C Chris Losinger
            const char \*p = "a,b,c,de,f,";
            int c = 0;
            for (;\*p;c+=(','==\*p++));
            

            image processing toolkits | batch image processing

            C Offline
            C Offline
            Cedric Moonen
            wrote on last edited by
            #6

            Ahh, the joys of C++. Did you make it so complex on purpose, or is all your code written like that ? ;P

            Cédric Moonen Software developer
            Charting control [v3.0] OpenGL game tutorial in C++

            I 1 Reply Last reply
            0
            • A AbhiHcl

              Hi I want to find the number of comma(,) in particular string. Like char* str = "a,b,c,d,e". So how many commas are there in str ? Thanks

              N Offline
              N Offline
              Nemanja Trifunovic
              wrote on last edited by
              #7

              [Untested]:

              std::string str("a, b, c, d, e");
              int count = std::count(str.begin(), str.end(), ',');

              or if you insist on C-style strings:

              int count = std::count(str, str + strlen(str), ',');

              utf8-cpp

              1 Reply Last reply
              0
              • A AbhiHcl

                Hi I want to find the number of comma(,) in particular string. Like char* str = "a,b,c,d,e". So how many commas are there in str ? Thanks

                M Offline
                M Offline
                Moak
                wrote on last edited by
                #8

                The inline ASM version is still missing, anyone? :D

                Chat in Europe :java: Now with 24% more Twitter

                E 1 Reply Last reply
                0
                • M Moak

                  The inline ASM version is still missing, anyone? :D

                  Chat in Europe :java: Now with 24% more Twitter

                  E Offline
                  E Offline
                  Emilio Garavaglia
                  wrote on last edited by
                  #9

                  I think is interesting to compare the solutions. Note: The "trivial" algorithm is to scan the string and count the ','. Now: Superman: Just did that using CRT: no additional data are added, and the strchr function is made walking from ',' to ','. Aescleal: Made an elegant use of STL algorithms. But: a constant literal is copied into a temporary std::string (probably with also a dynamic array allocated by the class itself), creates two temporary iterators, passing them to the std::count algorithm that just do the loop. Luc Pattyn: Use a more concise loop. Chris Losinger: same. Very elegant, but more cryptic. Nemanja Trifunovich: Same a Aescleal, but also propose to use std::cout with const char* instead of std::string::iterator-s, eliminating the need of the conversions. Moral of the story: I'm starting to believe that STL - and in particular "strings" are over-evaluated. The more coincise and elegant (together) is probably the second Nemanja proposal. But one question makes me wonder: Suppose I'm a coder asked to do this task, and suppose I know the algoritm, but i'm not expert in the language libraries: what should be fastest for me? - Read the STL documentation -probaly in strict alphabetic order- trying to guess is there can be something that can help me in counting the ',' (I'm luky the <algorithm> header come as first and the count function is one of the firsts ... estimated time: 15 minutes - but supposing I already know the "iterator"/"container"/"algorithm" model) - Just write

                  unsigned count_chars(const char* s, char d)
                  {
                  unsigned c=0;
                  for(unsigned int i=0; s[i]; ++i)
                  if(s[i]==d) ++c;
                  return c;
                  }

                  actual time 2 minutes! And the best of efficiency (no spurious allocation and copies) <sarcasm>Do yo understand the beauty of STL ?!?</sarcasm> (NOTE: using indexes, instead of incrementing pointers, is actually more efficient when translated into todays processor's code)

                  2 bugs found. > recompile ... 65534 bugs found. :doh:

                  M 1 Reply Last reply
                  0
                  • E Emilio Garavaglia

                    I think is interesting to compare the solutions. Note: The "trivial" algorithm is to scan the string and count the ','. Now: Superman: Just did that using CRT: no additional data are added, and the strchr function is made walking from ',' to ','. Aescleal: Made an elegant use of STL algorithms. But: a constant literal is copied into a temporary std::string (probably with also a dynamic array allocated by the class itself), creates two temporary iterators, passing them to the std::count algorithm that just do the loop. Luc Pattyn: Use a more concise loop. Chris Losinger: same. Very elegant, but more cryptic. Nemanja Trifunovich: Same a Aescleal, but also propose to use std::cout with const char* instead of std::string::iterator-s, eliminating the need of the conversions. Moral of the story: I'm starting to believe that STL - and in particular "strings" are over-evaluated. The more coincise and elegant (together) is probably the second Nemanja proposal. But one question makes me wonder: Suppose I'm a coder asked to do this task, and suppose I know the algoritm, but i'm not expert in the language libraries: what should be fastest for me? - Read the STL documentation -probaly in strict alphabetic order- trying to guess is there can be something that can help me in counting the ',' (I'm luky the <algorithm> header come as first and the count function is one of the firsts ... estimated time: 15 minutes - but supposing I already know the "iterator"/"container"/"algorithm" model) - Just write

                    unsigned count_chars(const char* s, char d)
                    {
                    unsigned c=0;
                    for(unsigned int i=0; s[i]; ++i)
                    if(s[i]==d) ++c;
                    return c;
                    }

                    actual time 2 minutes! And the best of efficiency (no spurious allocation and copies) <sarcasm>Do yo understand the beauty of STL ?!?</sarcasm> (NOTE: using indexes, instead of incrementing pointers, is actually more efficient when translated into todays processor's code)

                    2 bugs found. > recompile ... 65534 bugs found. :doh:

                    M Offline
                    M Offline
                    Moak
                    wrote on last edited by
                    #10

                    An interesting comparison, Emilio! My two cents. I think someone who has encountered this kind of problem before (data manipulation, string parsing) will need the equal amount of time for either a handcoded C-string solution (e.g. Luc's) or using a library solution (e.g. Aescleal's). Let's say 1 minute. Someone who does it the first time, would probably do the same as when I write something in a new language, you Google for examples and then use the first code snippet you like (probably it's not the best solution but a working one). Let's say 5 minutes. Cheers, M PS: The beauty of STL glows in less trivial examples. The iterator design pattern in particular is a nice idea in my opinion, it gives you a decoupling of data object and algorithm, e.g. you can use the same algorithm with a wide range of objects... and only have to learn it once = time saved.

                    Chat in Europe :java: Now with 24% more Twitter

                    E 1 Reply Last reply
                    0
                    • C Cedric Moonen

                      Ahh, the joys of C++. Did you make it so complex on purpose, or is all your code written like that ? ;P

                      Cédric Moonen Software developer
                      Charting control [v3.0] OpenGL game tutorial in C++

                      I Offline
                      I Offline
                      Iain Clarke Warrior Programmer
                      wrote on last edited by
                      #11

                      That was classic Kernighan and Richie C! Sheesh, youngsters of today... Whippersnapper! Iain.

                      I am one of "those foreigners coming over here and stealing our jobs". Yay me!

                      1 Reply Last reply
                      0
                      • M Moak

                        An interesting comparison, Emilio! My two cents. I think someone who has encountered this kind of problem before (data manipulation, string parsing) will need the equal amount of time for either a handcoded C-string solution (e.g. Luc's) or using a library solution (e.g. Aescleal's). Let's say 1 minute. Someone who does it the first time, would probably do the same as when I write something in a new language, you Google for examples and then use the first code snippet you like (probably it's not the best solution but a working one). Let's say 5 minutes. Cheers, M PS: The beauty of STL glows in less trivial examples. The iterator design pattern in particular is a nice idea in my opinion, it gives you a decoupling of data object and algorithm, e.g. you can use the same algorithm with a wide range of objects... and only have to learn it once = time saved.

                        Chat in Europe :java: Now with 24% more Twitter

                        E Offline
                        E Offline
                        Emilio Garavaglia
                        wrote on last edited by
                        #12

                        Moak wrote:

                        The beauty of STL glows in less trivial examples

                        Oh yes ... but reality is different: it is a matter of fact that vector (sequential indexed), list (sequential) and map (indexed) don't have same interfaces, and that the most of stl algorithm that are "non trivial" works with "sequential indexed" (aka "random access") iterators. Two siple example:

                        std::list<int> alist;
                        std::vector<int> avector;

                        alist.remove(10); //remove all 10s
                        avector.erase(std::remove(avector.begin(),avector.end(),10),avector.end());

                        Until someone doesn't demonstrate me how can I come to write the second example without having the knowledge of at least 20 pages of documentation (yes, I want a 8 y.o. baby coding that!), I will consider "you can use the same algorithm with a wide range of objects... and only have to learn it once = time saved." a pure marketing lye. (The fake is that vector doesn't have a remove function, hence is not dual to list, and std::remove doesn't remove: it just swaps things around. You cannot know that unless someone tells you) The pattern itself can be a good idea (iterators as a bridge between collections and algorithms) but the way is implemented is far from being obvious. That's the point i was considering.

                        2 bugs found. > recompile ... 65534 bugs found. :doh:

                        M 1 Reply Last reply
                        0
                        • E Emilio Garavaglia

                          Moak wrote:

                          The beauty of STL glows in less trivial examples

                          Oh yes ... but reality is different: it is a matter of fact that vector (sequential indexed), list (sequential) and map (indexed) don't have same interfaces, and that the most of stl algorithm that are "non trivial" works with "sequential indexed" (aka "random access") iterators. Two siple example:

                          std::list<int> alist;
                          std::vector<int> avector;

                          alist.remove(10); //remove all 10s
                          avector.erase(std::remove(avector.begin(),avector.end(),10),avector.end());

                          Until someone doesn't demonstrate me how can I come to write the second example without having the knowledge of at least 20 pages of documentation (yes, I want a 8 y.o. baby coding that!), I will consider "you can use the same algorithm with a wide range of objects... and only have to learn it once = time saved." a pure marketing lye. (The fake is that vector doesn't have a remove function, hence is not dual to list, and std::remove doesn't remove: it just swaps things around. You cannot know that unless someone tells you) The pattern itself can be a good idea (iterators as a bridge between collections and algorithms) but the way is implemented is far from being obvious. That's the point i was considering.

                          2 bugs found. > recompile ... 65534 bugs found. :doh:

                          M Offline
                          M Offline
                          Moak
                          wrote on last edited by
                          #13

                          Please have a breakfast before making angry morning postings. :)

                          Chat in Europe :java: Now with 24% more Twitter

                          1 Reply Last reply
                          0
                          Reply
                          • Reply as topic
                          Log in to reply
                          • Oldest to Newest
                          • Newest to Oldest
                          • Most Votes


                          • Login

                          • Don't have an account? Register

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • World
                          • Users
                          • Groups