3 Replies - 387 Views - Last Post: 26 January 2013 - 08:50 AM Rate Topic: -----

#1 zohaibuu  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 24-November 12

How to find word in a string

Posted 26 January 2013 - 07:45 AM

I m working how to make a program to find word in a string. for this i posted my code it has logical error can any tell me what to do next?? i m tokenizing string after that what to do? thanks in advance..

#include <iostream>
#include <cstring>

using namespace std;

void main()
{
	char string[100], keyword[100], *string_ptr = string, *keyword_ptr=keyword;

	cout << "Enter sentence\n";
	cin.getline(string_ptr,100,'\n');

	cout << "Enter search word\n";
	cin.getline(keyword_ptr,100,'\n');

	string_ptr = strtok(string, " ");
	
	while (string_ptr != NULL)
	{
		//cout << string_ptr <<endl;
		string_ptr = strtok(NULL , " ");
	}

	keyword_ptr = strtok(keyword, " ");

	while (keyword_ptr != NULL)
	{
		//cout << keyword_ptr << endl;
		keyword_ptr = strtok(NULL , " ");
	}


	
}




Is This A Good Question/Topic? 0
  • +

Replies To: How to find word in a string

#2 jimblumberg  Icon User is offline

  • member icon


Reputation: 4018
  • View blog
  • Posts: 12,400
  • Joined: 25-December 09

Re: How to find word in a string

Posted 26 January 2013 - 08:05 AM

Is there a reason you are using C-strings instead of std::string? Using std::string should make things much easier.

Jim
Was This Post Helpful? 0
  • +
  • -

#3 zohaibuu  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 24-November 12

Re: How to find word in a string

Posted 26 January 2013 - 08:13 AM

now if we use std::string then what is the logic can u help me??
Was This Post Helpful? 0
  • +
  • -

#4 jimblumberg  Icon User is offline

  • member icon


Reputation: 4018
  • View blog
  • Posts: 12,400
  • Joined: 25-December 09

Re: How to find word in a string

Posted 26 January 2013 - 08:50 AM

Use a stringstream and the stream extraction operator>> to extract "words" from the string.

vector<string> words;
string line("This is a test string");
istringsteam ins(line);
string temp;
while(ins >> temp)
   words.push_back(temp);




Jim
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1