You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash中如何在if语句内比较两个字符串变量的长度是否匹配

字符串长度比较的if语句实现方案

以下是不同常用开发场景下的实现方式:

Shell 脚本

通过${#变量名}语法获取字符串长度,写法如下:

# 示例变量赋值
string_one="hello"
string_two="worldtest"

# 长度比较逻辑
if [ ${#string_one} -ne ${#string_two} ]; then
    # 此处写长度不等时的执行逻辑
    echo "两个字符串长度不一致"
fi

如果使用[[ ]]语法,也可以直接用!=运算符:

if [[ ${#string_one} != ${#string_two} ]]; then
    # 执行逻辑
fi

Python

直接调用内置len()函数即可,和你给出的伪代码逻辑完全匹配:

string_one = "测试内容1"
string_two = "测试内容较长的2"

if len(string_one) != len(string_two):
    # 此处写长度不等时的执行逻辑
    print("两个字符串长度不一致")

Perl

你给出的伪代码本身就接近Perl原生语法,直接用内置length()函数即可:

my $string_one = "测试内容1";
my $string_two = "测试内容较长的2";

if (length($string_one) != length($string_two)) {
    # 此处写长度不等时的执行逻辑
    print "两个字符串长度不一致\n";
}

内容的提问来源于stack exchange,提问作者artnikpro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 21:24:00