MST
星途 面试题库

面试题:Bash字符串搜索与替换的复杂应用

有一个Bash脚本,其中定义了一个长字符串text='The old dog runs fast. The old cat jumps high. The old bird flies away',要求编写代码将字符串中所有出现的'old'替换为'young',并且将替换后的字符串按句子(以句号.分隔)拆分成数组,然后遍历数组并输出每个句子的长度。
48.7万 热度难度
编程语言Bash

知识考点

AI 面试

面试题答案

一键面试
#!/bin/bash

text='The old dog runs fast. The old cat jumps high. The old bird flies away'
new_text=${text//old/young}
sentences=(${new_text//./ })

for sentence in "${sentences[@]}"; do
    length=${#sentence}
    echo "句子长度: $length"
done