不使用分支判断类语法的字符串长度比较及结果展示方法问询
不使用分支判断类语法的字符串长度比较及结果展示方法问询
嘿,这个问题挺有巧思的——要完全避开if、switch、三元运算符这类分支判断语法,找出两个字符串里更长的那个还得展示它的长度,我给你分享几个实用的实现思路和代码示例吧!
方法一:利用数组排序特性(多语言通用思路)
核心逻辑是把两个字符串放进数组,通过基于长度的排序让更长的字符串自动跑到固定索引位置,直接取值就行,全程不用任何分支判断。
比如JavaScript的实现:
function showLongerString(str1, str2) { // 按字符串长度升序排序,长的会排在数组末尾 const sortedStrings = [str1, str2].sort((a, b) => a.length - b.length); const longerStr = sortedStrings[1]; console.log(`更长的字符串是:"${longerStr}",长度为 ${longerStr.length}`); } // 测试一下 showLongerString("Hello World", "Stack Exchange"); // 会输出后者的信息 showLongerString("Apple", "Banana"); // 输出Banana的信息
如果是Python,排序逻辑类似:
def show_longer_string(str1, str2): # 按长度升序排序,取最后一个元素就是更长的 sorted_strings = sorted([str1, str2], key=lambda s: len(s)) longer_str = sorted_strings[-1] print(f"更长的字符串是:\"{longer_str}\",长度为 {len(longer_str)}") # 测试调用 show_longer_string("Python", "JavaScript")
方法二:利用布尔值转数字的语言特性
有些编程语言里布尔值可以直接转换为整数(比如Python、JavaScript中True对应1,False对应0),我们可以利用这个特性直接计算出更长字符串的索引。
Python示例:
def show_longer_string(str1, str2): # 当str2更长时,len(str2) > len(str1)为True,转成整数1;否则为0 target_index = int(len(str2) > len(str1)) longer_str = [str1, str2][target_index] print(f"更长的字符串是:\"{longer_str}\",长度为 {len(longer_str)}")
JavaScript示例:
function showLongerString(str1, str2) { // JavaScript中布尔值转数字用Number(),或者+号 const targetIndex = Number(str2.length > str1.length); const longerStr = [str1, str2][targetIndex]; console.log(`更长的字符串是:"${longerStr}",长度为 ${longerStr.length}`); }
这两种方法都完美避开了所有分支判断语法,而且逻辑清晰,对长度相等的情况也能正常处理(会取其中一个字符串,符合题目要求)。
内容来源于stack exchange
相关产品推荐
相关产品推荐

