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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 00:32:02