String matching: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
Line 10: Line 10:
A) Print the location of the match for part 2
A) Print the location of the match for part 2
B) Handle multiple occurrences of a string for part 2.
B) Handle multiple occurrences of a string for part 2.

=={{header|C++}}==

<lang cpp>
#include <string>

string s1="abcd";
string s2="abab";
string s3="ab";
//Beginning
s1.compare(0,s3.size(),s3)!=0;
//End
s1.compare(s1.size()-s3.size(),s3.size(),s3)!=0;
//Anywhere
s1.find(s2)//returns string::npos
int loc=s2.find(s3)//returns 0
loc=s2.find(s3,loc+1)//returns 2
</lang>


=={{header|Python}}==
=={{header|Python}}==
Line 16: Line 34:
"abcd".startswith("ab")#returns true
"abcd".startswith("ab")#returns true
"abcd".endswith("zn")#returns false
"abcd".endswith("zn")#returns false
location="abab".find("ab")#returns 0
loc="abab".find("bb")#returns -1
location="abab".find("ab",location+1)#returns 2
loc="abab".find("ab")#returns 0
loc="abab".find("ab",loc+1)#returns 2
</lang>
</lang>

Revision as of 03:38, 15 October 2010

Task
String matching
You are encouraged to solve this task according to the task description, using any language you may know.

Given two strings, demonstrate the following 3 types of matchings:

1. Determining if the first string starts with second string 2. Determining if the first string contains the second string at any location 3. Determining if the first string ends with the second string

Optional requirements: A) Print the location of the match for part 2 B) Handle multiple occurrences of a string for part 2.

C++

<lang cpp>

  1. include <string>

string s1="abcd"; string s2="abab"; string s3="ab"; //Beginning s1.compare(0,s3.size(),s3)!=0; //End s1.compare(s1.size()-s3.size(),s3.size(),s3)!=0; //Anywhere s1.find(s2)//returns string::npos int loc=s2.find(s3)//returns 0 loc=s2.find(s3,loc+1)//returns 2 </lang>

Python

<lang python> "abcd".startswith("ab")#returns true "abcd".endswith("zn")#returns false loc="abab".find("bb")#returns -1 loc="abab".find("ab")#returns 0 loc="abab".find("ab",loc+1)#returns 2 </lang>