题目描述补充
题目:比较字符串
给定两个字符串str1
和str2
,你需要编写一个函数来比较这两个字符串。该函数需要支持以下操作:
- 相等性比较:如果
str1
和str2
完全相同(包括大小写和字符顺序),则返回true
;否则返回false
。 - 忽略大小写比较:在比较时忽略字符串中的大小写差异,如果忽略大小写后
str1
和str2
相同,则返回true
;否则返回false
。
示例代码
PHP 示例
<?php
function compareStrings($str1, $str2, $ignoreCase = false) {
if ($ignoreCase) {
return strtolower($str1) === strtolower($str2);
}
return $str1 === $str2;
}
// 测试代码
echo compareStrings("Hello", "Hello") ? "true" : "false"; // 输出 true
echo "\n";
echo compareStrings("Hello", "hello", true) ? "true" : "false"; // 输出 true
?>
Python 示例
def compare_strings(str1, str2, ignore_case=False):
if ignore_case:
return str1.lower() == str2.lower()
return str1 == str2
# 测试代码
print(compare_strings("Hello", "Hello")) # 输出 True
print(compare_strings("Hello", "hello", True)) # 输出 True
JavaScript 示例
function compareStrings(str1, str2, ignoreCase = false) {
if (ignoreCase) {
return str1.toLowerCase() === str2.toLowerCase();
}
return str1 === str2;
}
// 测试代码
console.log(compareStrings("Hello", "Hello")); // 输出 true
console.log(compareStrings("Hello", "hello", true)); // 输出 true
额外内容分享
码小课网站中有更多关于字符串处理、算法设计以及编程面试技巧的相关内容分享给大家学习。无论你是初学者还是有一定经验的开发者,都能在这里找到适合自己的学习资源,帮助你不断提升编程技能。