給定英文句子,將每個單字的最後一個字母大小寫互換(大變小、小變大),標點符號(, ' " . ;)不變,縮寫形式(如 can't)視為單一單字處理。本文提供完整演算法實作與測試案例。
"A journey of, a thousand 'miles' must can't \"begin\" with a single step.""a journeY oF, A thousanD 'mileS' musT can'T "begiN" witH A singlE steP."can't 視為一個單字,尾字母 t 互換, ' " . ; 後若有空格則視為單字結尾<?php
function convertLastChar($str) {
// 標點+空格組合,標記單字結尾
$markArr = [", ", "' ", "\" ", ". ", "; "];
$ret = "";
$len = strlen($str);
for ($i = 0; $i < $len; $i++) {
// 取得後續兩字元(含邊界保護)
if ($i < $len - 2) {
$afterStr = $str[$i + 1] . $str[$i + 2];
} elseif ($i < $len - 1) {
$afterStr = $str[$i + 1] . " ";
} else {
$afterStr = " "; // 字串結尾
}
// 判斷目前字元是否為單字尾字母
$isLastChar = in_array($afterStr, $markArr)
|| $i == $len - 1
|| $str[$i + 1] == " ";
if ($isLastChar) {
// 大小寫互換
$char = $str[$i];
$ret .= (strtoupper($char) === $char)
? strtolower($char)
: strtoupper($char);
} else {
$ret .= $str[$i];
}
}
return $ret;
}
?>
<?php
$tests = [
"A journey of, a thousand 'miles' must can't \"begin\" with a single step.",
"A journey of, a thousand 'miles' must can't \"begin\" with a single step. ",
"A journey of, a thousand 'miles' must can't \"begin\" with a single step. a ",
"A journey of, a thousand 'miles' must can't \"begin\" with a single step. a B",
"A journey of, a thousand 'miles' must can't \"begin\" with a single step. a b'",
"A journey of, a thousand 'miles' must can't \"begin\" with a single step. a B\""
];
foreach ($tests as $idx => $str) {
echo "Test " . ($idx+1) . ":\n";
echo "Source: $str\n";
echo "Result: " . convertLastChar($str) . "\n\n";
}
?>
Test 1:
Source: A journey of, a thousand 'miles' must can't "begin" with a single step.
Result: a journeY oF, A thousanD 'mileS' musT can'T "begiN" witH A singlE steP.
Test 2:
Source: A journey of, a thousand 'miles' must can't "begin" with a single step.
Result: a journeY oF, A thousanD 'mileS' musT can'T "begiN" witH A singlE steP.
Test 3:
Source: A journey of, a thousand 'miles' must can't "begin" with a single step. a
Result: a journeY oF, A thousanD 'mileS' musT can'T "begiN" witH A singlE steP. A
Test 4:
Source: A journey of, a thousand 'miles' must can't "begin" with a single step. a B
Result: a journeY oF, A thousanD 'mileS' musT can'T "begiN" witH A singlE steP. A b
Test 5:
Source: A journey of, a thousand 'miles' must can't "begin" with a single step. a b'
Result: a journeY oF, A thousanD 'mileS' musT can'T "begiN" witH A singlE steP. A B'
Test 6:
Source: A journey of, a thousand 'miles' must can't "begin" with a single step. a B"
Result: a journeY oF, A thousanD 'mileS' musT can'T "begiN" witH A singlE steP. A b"
$i+1 和 $i+2 位置,識別「標點+空格」組合作為單字邊界can't 中 ' 後無空格,不觸發邊界判斷,t 正確被識別為尾字母strtoupper($char) === $char 避免 ctype_upper() 受 locale 影響mb_strlen/mb_substr + mb_strtoupper)此演算法展示字串逐字元掃描配合向前看策略,解決自然語言邊界識別的典型技巧。