简体   繁体   中英

Check if a string is made up of multiple occurences of a substring

(JavaScript) So, I need a function checkString(str, substr) that checks whether a string is made out of multiple occurences of a given substring.
Examples:
checkString("abc", "abc") -> true
checkString("abcabcabc", "abc") -> true
checkString("abcdef", "abc") -> false
checkString("abcab", "abc) -> true
Could someone help me out?

If whitespaces don't matter, this is a solution:

const checkString = (bigString, subString) => {
  const split = bigString.split(subString);
  const onlyOccurances = split.filter(v => v === '');

  return split.length === onlyOccurances.length
}

checkString("abc", "abc") // true
checkString("abcabcabc", "abc") // true
checkString("abcdef", "abc") // false

bigString.split(subString) will split the big string into an array of empty strings if there's perfect match, and the length of it will be exactly how many occurances there are. If any of the values in the array are not empty strings, it means there is not a perfect match so there will be a difference between the length of the filtered by empty and the length of the splited values.

Hope it makes sense.

This method will return an object and found will be true if the value is found in the string and multipleFound will be true if found more than once;

const checkString = function(str, v) {
let found = false,
    multi = false,
    index;
index = str.indexOf(v);
if (index !== -1) {
    found = true;
    index = str.indexOf(v, index + v.length);
    if (index !== -1) {
        multi = true;
    }
}
return {
    found : found,
    multipleFound : multi
};

};

This would be one way to check against the pattern abc :

 const rx=/^(abc)+$/; console.log(["abc","abcabcabc","abcdef"].map(t=> `${t} ${rx.test(t)}`))

I highly recommend sharpening your algorithm skills on a site like leetcode.com

Here's what I came up with

function checkString(whole, sub) {
  for (let i = 0; i < whole.length; i++) {
    if (whole[i] !== sub[i % sub.length]) {
      return false;
    }
  }
  return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM