How to use Substring Method and Set In Javascript
In this approach, we utilize the substring method to divide the string into four equal segments. We then store these segments in a set data structure, which automatically removes duplicate entries. By checking the size of the set, we can determine if the string can be split into four distinct substrings.
Example:
function canSplitIntoFourDistinctStrings(str) {
if (str.length % 4 !== 0) {
return false; // If the length is not divisible by 4, it cannot be split into four equal segments
}
const segmentLength = str.length / 4;
const segments = new Set(); // Using Set to store unique segments
for (let i = 0; i < str.length; i += segmentLength) {
const segment = str.substring(i, i + segmentLength);
segments.add(segment);
}
return segments.size === 4; // If there are four unique segments, return true
}
console.log(canSplitIntoFourDistinctStrings("abcdefgh"));
console.log(canSplitIntoFourDistinctStrings("abcdabcdabcdabcd"));
Output
true false
JavaScript Program to Check if Given String can be Split into Four Distinct Strings
A string can be split into four distinct strings by identifying specific delimiters or patterns within the original string and extracting substrings based on these divisions, resulting in four separate and non-overlapping text segments. In this article, we will check if a given string can be split into four distinct strings.
Table of Content
- Using Regular Expression
- Using Recursive Method
- Using The Length Property
- Using Sorting
- Using Substring Method and Set
Contact Us