How to use The Length Property In Javascript
In this approach, we are using the length property to divide input strings into four equal segments. It checks if the length is divisible by 4 and creates substrings. It ensures each substring’s uniqueness and equal length, determining if the input can be split into four distinct strings.
Example: In this example, we check if a given string can be split into four equal-length, distinct substrings. It verifies divisibility by 4, creates substrings, and ensures uniqueness.
let str1 = "w3wiki";
let str2 = "w3wikiExample";
function isDistinct(str) {
if (str.length % 4 !== 0) {
return false;
}
let length = str.length / 4;
let substrings = {};
let i = 0;
for (const char of str) {
if (i % length === 0) {
let substring = str.substring(i, i + length);
if (substrings[substring] ||
substring.length !== length) {
return false;
}
substrings[substring] = true;
}
i++;
}
return Object.keys(substrings).length === 4;
}
console.log(`String: "${str1}"`);
if (isDistinct(str1)) {
console.log(`result: The string can be
split into four distinct strings.`);
} else {
console.log(`result: The string cannot be
split into four distinct strings.`);
}
console.log(`\nString: "${str2}"`);
if (isDistinct(str2)) {
console.log(`result: The string can be
split into four distinct strings.`);
} else {
console.log(`result: The string cannot
be split into four distinct strings.`);
};
Output
String: "w3wiki" result: The string cannot be split into four distinct strings. String: "w3wikiExample" result: The string can be split into four distinct strings.
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