Check If One String Is a Prefix of Another

Check if one string is a prefix of another

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.
}

Determine if one string is a prefix of another

Looks like you've got two different problems.

One is to determine if a string is contained as a prefix in another string. For this I would suggest using a function already implemented in the language's string library. In JavaScript you could do this

if (str2.indexOf(str1) === 0) {
// string str1 is a prefix of str2
}

See documentation for String.indexOf here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

For the other problem, in a bunch of strings, find out which ones have a given string as a prefix, building a data structure like a Trie or the one you mention seems like the way to go, if you want fast look-ups.

Given a list of string, determine if one string is a prefix of another string

Let us first sort the given lst w.r.t length of the string, due to the known fact that sub strings always have length less than or equal to the original string, so after sorting we have strings with smaller length at the start of the list, and then we iterate over the sorted list comparing the current element with all the elements next to it, This small optimization would reduce the complexity of the problem as now we don't have to comapre each element with every other element.

lst1 = ['abc', 'abcd', 'xyx', 'mno']
lst2 = ['abc', 'xyzabc', 'mno']
lst3 = ["abc", "abc"]

def check_list(lst):
lst = list(set(lst)) #if you want to avoid redundant strings.
lst.sort(key = lambda x:len(x))

n = len(lst)
for i in xrange(n):
for j in xrange(i+1, n):
if lst[j].startswith(lst[i]):
return True
return False

print check_list(lst1)
print check_list(lst2)
print check_list(lst3)
>>> True
>>> False
>>> False #incase you use lst = list(set(lst))

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

Use rfind overload that takes the search position pos parameter, and pass zero for it:

std::string s = "tititoto";
if (s.rfind("titi", 0) == 0) { // pos=0 limits the search to the prefix
// s starts with prefix
}

Who needs anything else? Pure STL!

Many have misread this to mean "search backwards through the whole string looking for the prefix". That would give the wrong result (e.g. string("tititito").rfind("titi") returns 2 so when compared against == 0 would return false) and it would be inefficient (looking through the whole string instead of just the start). But it does not do that because it passes the pos parameter as 0, which limits the search to only match at that position or earlier. For example:

std::string test = "0123123";
size_t match1 = test.rfind("123"); // returns 4 (rightmost match)
size_t match2 = test.rfind("123", 2); // returns 1 (skipped over later match)
size_t match3 = test.rfind("123", 0); // returns std::string::npos (i.e. not found)

How to check if a string starts with another string in C?

Apparently there's no standard C function for this. So:

bool startsWith(const char *pre, const char *str)
{
size_t lenpre = strlen(pre),
lenstr = strlen(str);
return lenstr < lenpre ? false : memcmp(pre, str, lenpre) == 0;
}

Note that the above is nice and clear, but if you're doing it in a tight loop or working with very large strings, it does not offer the best performance, as it scans the full length of both strings up front (strlen). Solutions like wj32's or Christoph's may offer better performance (although this comment about vectorization is beyond my ken of C). Also note Fred Foo's solution which avoids strlen on str (he's right, it's unnecessary if you use strncmp instead of memcmp). Only matters for (very) large strings or repeated use in tight loops, but when it matters, it matters.

How to check if a string begins with prefix and contains specific keyword in Ruby

The code looks good. The only feedback I have is regarding the use of 'include?' function for the prefix. Try to use 'start_with?' function instead, so that you don't get True even when the the "Dr" is within the string.

def match st
if st.start_with?('Dr.') and st.include?('Alex')
return true
else
return false
end
end

How to check prefixes in a string with dots separator

It took me a while to figure out the pattern. Apparently you want to look at each sub-component individually and only return true if the sub-component is not matching. It appears that if there are more sub-components, that it is not being checked/scanned towards the parent string.

Eventually I got this function

function test(p, c) {
const pSplit = p.split('.');
const cSplit = c.split('.');
const maxLen = pSplit.length; // I guess parent has always min # of parts
for(let i = 0; i < maxLen; ++i) {
if (pSplit[i] !== cSplit[i]) return true;
}
return false;
}

Interactive example:

function test(p, c) {  const pSplit = p.split('.');  const cSplit = c.split('.');  const maxLen = pSplit.length; // I guess parent has always min # of parts  for(let i = 0; i < maxLen; ++i) {    if (pSplit[i] !== cSplit[i]) return true;  }  return false;}

console.log('expected to be false');console.log(test("abc.xyz","abc.xyz.pol"));console.log(test("abc.xyz","abc.xyz.pol.del"));console.log(test("abc.xyz.pol","abc.xyz.pol.del"));
console.log('expected to be true');console.log(test("abc.xyz.pol","abc.xyz.del"));console.log(test("abc.xyz","abc.xyzDel"));console.log(test("abc.xyz","abc.xyzDel.pol"));


Related Topics



Leave a reply



Submit