How to sort the words in a string with TypeScript

1 Answer

0 votes
function sortTheWordsInAString(s: string) {
    let arr: string[] = s.split(" ");

    arr.sort();

    let result: string = "";
    for (let str of arr) {
        result += str + " ";
    }

    if (result.length > 0) {
        result = result.slice(0, -1); // Remove the last space
    }

    return result;
}

let s: string = "php c typescript c++ python c#";

s = sortTheWordsInAString(s);

console.log(s);



/*
run:
    
"c c# c++ php python typescript" 
    
*/

 



answered Jul 29, 2024 by avibootz
...