[英]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.拼写器部分很简单(使用 PHP 的 pspell 库),但我无法解决的是大小写问题。
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).假设拼错的词是“GoVeNMeNt”,那么正确的词应该是“GoVerNMeNt”(类似于谷歌),但pspell 库仅在一种情况下(通常是小写)给出建议。
So how do I write a function transformCase
which takes in the actual string ( $string
) and the suggestion string ( $subject
)?那么我如何编写一个函数transformCase
来接收实际字符串( $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.在最后一种情况下,输出应该是 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.比较elseif (strlen($string)==strlen($subject))
不保证该函数按您的需要工作。 Otherwise, you can introduce additional modifications for a best performance.否则,您可以引入额外的修改以获得最佳性能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.