how do I convert a string to char array to find a substring within a string?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • red222
    New Member
    • Mar 2010
    • 2

    how do I convert a string to char array to find a substring within a string?

    I am trying to find a string within a substring using strstr. This only works with char arrays. I have an array of objects of which I am searching a particular property which is a string.
    Code:
    char *strPtr;
    	
    	int index = 0;
    	bool located = false;
    
    	do
    	{
    		for(index = 0; index <NUM_BOOKS; index ++)
    		{
    			strPtr = strstr(bookList[index].getTitle(), book);//str1, str2);
    			if(strPtr == NULL)
    			{
    				cout << "No matching titles were found.\n";
    			}
    			else
    			{
    				located = true;
    				found.push_back(index);
    			}
    		}
    		
    	}while(index < NUM_BOOKS && !located);
    I am using C++
    Last edited by RedSon; Mar 9 '10, 10:43 PM. Reason: Rule #1 of posting questions, no one is going to read it if you don't make your code look nice. USE [CODE] TAGS!
  • whodgson
    Contributor
    • Jan 2007
    • 542

    #2
    If you declare string s you can then use getline(cin,s) to load a string to s from the keyboard.
    You can print the string with cout<<s;
    string s1;//declare s1.
    You can get a substring from s with for example s1=s.substr(5,1 4) s1 gets the 6th element in the array s[] plus the next 13 characters including spaces.
    cout<<s1;//prints s1 which is 14 characters long starting with the 6th element in array s.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      This is C++ and not C so don't use strstr.

      What you want is the find_first_of algorithm. You pass in your collection of objects plus a function pointer to a function that returns a bool if your search criteria are met or not.

      Comment

      • red222
        New Member
        • Mar 2010
        • 2

        #4
        Originally posted by weaknessforcats
        This is C++ and not C so don't use strstr.

        What you want is the find_first_of algorithm. You pass in your collection of objects plus a function pointer to a function that returns a bool if your search criteria are met or not.
        Do you have any examples you could show me? I'm not exactly sure what you are saying.

        Comment

        • jkmyoung
          Recognized Expert Top Contributor
          • Mar 2006
          • 2057

          #5

          Comment

          Working...