Scala中如何移除字符串最后一个点之后的部分?
解决方案
下面提供几种主流编程语言的通用实现方式,无需硬编码字符串,可处理任意格式一致的输入:
Python
可以用rsplit()方法从右侧分割一次,取分割后的第一部分:
s = "108.0.5359.124" result = s.rsplit('.', 1)[0] print(result) # 输出: 108.0.5359
或者用rfind()找到最后一个点的索引,再截取前面的子串(还能兼容字符串中没有点的情况):
s = "108.0.5359.124" last_dot_idx = s.rfind('.') result = s[:last_dot_idx] if last_dot_idx != -1 else s print(result)
JavaScript
利用lastIndexOf()定位最后一个点的位置,再通过slice()截取目标内容:
const s = "108.0.5359.124"; const lastDotIdx = s.lastIndexOf('.'); const result = lastDotIdx !== -1 ? s.slice(0, lastDotIdx) : s; console.log(result); // 输出: 108.0.5359
Bash
借助Shell参数扩展特性,直接移除最后一个点及之后的内容:
s="108.0.5359.124" result="${s%.*}" echo $result # 输出: 108.0.5359
内容的提问来源于stack exchange,提问作者sarah w
相关产品推荐
相关产品推荐

