Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if one string is a prefix of another

I have two strings which I'd like to compare: String and String:. Is there a library function that would return true when passed these two strings, but false for say String and OtherString?

To be precise, I want to know whether one string is a prefix of another.

like image 466
fredley Avatar asked Oct 27 '11 09:10

fredley


People also ask

How do you check if a string is a prefix of another string Java?

Java String startsWith() method is used to check the prefix of string. It verifies if given string starts with argument string or not. startsWith() method is overloaded method and has two forms: boolean startsWith(String str) – returns true if the str is a prefix of the String.

How do you check a string is a prefix of another string in Python?

The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False .

How do you find the prefix of a string?

A prefix of a string S is any leading contiguous part of S. A suffix of the string S is any trailing contiguous part of S. For example, "c" and "cod" are prefixes, and "ty" and "ity" are suffixes of the string "codility".


1 Answers

Use std::mismatch. Pass in the shorter string as the first iterator range and the longer as the second iterator range. The return is a pair of iterators, the first is the iterator in the first range and the second, in the second rage. If the first is end of the first range, then you know the the short string is the prefix of the longer string e.g.

std::string foo("foo"); std::string foobar("foobar");  auto res = std::mismatch(foo.begin(), foo.end(), foobar.begin());  if (res.first == foo.end()) {   // foo is a prefix of foobar. } 
like image 160
Nim Avatar answered Oct 06 '22 03:10

Nim