How to split a string into words. Ex: “stringintowords” -> “String Into Words”?

前端 未结 13 1199
粉色の甜心
粉色の甜心 2020-11-29 20:18

What is the right way to split a string into words ? (string doesn\'t contain any spaces or punctuation marks)

For example: \"stringintowords\" -> \"String Into Word

相关标签:
13条回答
  • 2020-11-29 20:43

    I was looking at the problem and thought maybe I could share how I did it. It's a little too hard to explain my algorithm in words so maybe I could share my optimized solution in pseudocode:

    string mainword = "stringintowords";
    array substrings = get_all_substrings(mainword);
    
    /** this way, one does not check the dictionary to check for word validity 
     *  on every substring; It would only be queried once and for all, 
     *  eliminating multiple travels to the data storage
     */
    string query = "select word from dictionary where word in " + substrings;
    array validwords = execute(query).getArray();
    
    validwords = validwords.sort(length, desc);
    
    array segments = [];
    while(mainword != ""){
        for(x = 0; x < validwords.length; x++){
            if(mainword.startswith(validwords[x])) {
                segments.push(validwords[x]);
                mainword = mainword.remove(v);
                x = 0;
            }
        }
    
        /**
         * remove the first character if any of valid words do not match, then start again
         * you may need to add the first character to the result if you want to
         */
        mainword = mainword.substring(1);
    }
    
    string result = segments.join(" ");
    
    0 讨论(0)
提交回复
热议问题