Can you give a string partitioning example?

Certainly! Here's an example of string partitioning in JavaScript, where we split a string into substrings based on a specific delimiter, such as a space.

Example: Partitioning a String by Spaces

let str = "Hello world this is Labby";
let partitions = str.split(" ");
console.log(partitions);

Output:

[ 'Hello', 'world', 'this', 'is', 'Labby' ]

In this example, the split(" ") method is used to partition the string into an array of words, using spaces as the delimiter. Each word becomes an element in the resulting array.

Example: Partitioning a String into Palindromes

If you want to partition a string into palindromic substrings, you can use a function to check for palindromes:

function isPalindrome(s) {
    return s === s.split('').reverse().join('');
}

function partitionPalindromes(str) {
    let result = [];
    let words = str.split(" ");
    
    for (let word of words) {
        if (isPalindrome(word)) {
            result.push(word);
        }
    }
    
    return result;
}

let str = "madam racecar hello level";
let palindromicPartitions = partitionPalindromes(str);
console.log(palindromicPartitions);

Output:

[ 'madam', 'racecar', 'level' ]

In this example, the partitionPalindromes function splits the string into words and checks each word to see if it is a palindrome, collecting the palindromic words into an array.

0 Comments

no data
Be the first to share your comment!