Tuesday, March 21, 2023

Coding Challenge #28

 // from https://www.codecademy.com/resources/blog/20-code-challenges/
// reverse the order of words in a sentence, while maintaining punctuation
// we will maintain the punctuation '.' ',', '?', and '!'.
function reverse(str){
    var words = str.split(" ");
    // extract punctuation and keep it in an array
    var puncs = []; // store info of what punctuation is at which char in the word
    for(var xint = 0;xint < words.length;xint++){
        var punc = '';
        for(var yint = 0, len = words[xint].length;yint < len;yint++){
            var c = words[xint].charAt(yint);
            if(c == '.' || c == ',' || c == '?' || c == '!'){
                punc = c;
            }
        }
        puncs.push(punc);
        words[xint] = words[xint].replaceAll('.','').replaceAll(',','').replaceAll('?','').replaceAll('!',''); // remove punctuation
    }
    
    // rearrange words (reverse order)
    var words_rev = [];
    for(var xint = words.length - 1;xint > -1;xint--)
        words_rev.push(words[xint]);
        
    
    // place back in the punctuation
    for(var xint = 0;xint < words_rev.length;xint++){
        words_rev[xint] += puncs[xint];
    }
    
    
    var o = "";
    if(words_rev.length > 0){
        o += words_rev[0];
    }
    for(var xint = 1;xint < words_rev.length;xint++){
        o += " " + words_rev[xint];
    }
    return o;
}

function test(str){
    console.log("Pre : " + str + "\nPost: " + reverse(str));
}

test("Hi, there, friend.");
test("How are you today?");
test("I think, and therefore I am. How about you? Cool!");

No comments:

Post a Comment

Coding Challenge #54 C++ int to std::string (no stringstream or to_string())

Gets a string from an integer (ejemplo gratis: 123 -> "123") Wanted to come up with my own function for this like 10 years ago ...