简体   繁体   中英

How to change a string's case based on another string?

I'm working on a " Do you mean ... " kinda system similar to Google! The speller part is trivial (with PHP's pspell library) but what I can't solve is the case problem.

Let's say the mispelled word is "GoVeNMeNt" then the correct word should be "GoVerNMeNt" (similar to Google), but pspell library gives suggestions only in one-case (lower-case usually).

So how do I write a function transformCase which takes in the actual string ( $string ) and the suggestion string ( $subject )? I have written the following implementation which doesn't handle all cases:

function transformCase($string,$subject){
    for ($i=0,$marker=0;$i<strlen($string);++$i)
        if (strcasecmp($string[$i],$subject[$marker])==0){
            $subject[$marker]=$string[$i];
            $marker+=1;
        }
        elseif (strlen($string)==strlen($subject))
            $marker+=1;
    return $subject;
}
echo transformCase("AbSaNcE",'absence')."\n";  # AbSeNcE :)
echo transformCase("StRioNG",'string')."\n";   # StRiNG  :)
echo transformCase("GOVERMENt",'government')."\n"; # GOVERNment :<

In the last case the output should be GOVERnMENt. The algorithm also doesn't work on various other queries.

So I'd be happy if someone helps me with the algorithm :)

Try the next modification to your algorithm:

function transformCase($string,$subject) {
    for ($i=0,$marker=0;$i<strlen($string);++$i) {
        if (strcasecmp($string[$i],$subject[$marker])==0) {
            $subject[$marker]=$string[$i];
            $marker+=1;
        }
        // Look for the next same character in $string
        while (strcasecmp($string[$i],$subject[$marker])!=0) {
            $i+=1;
        }
    }
    return $subject;
}

The comparisson elseif (strlen($string)==strlen($subject)) don't warrant the function to work as you need. Otherwise, you can introduce additional modifications for a best performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM