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

如何优化重复从字符串末尾截断至指定分隔符的C#代码实现?

优化字符串末尾截取至指定分隔符的实现

你的需求是每次调用方法时,移除字符串最后一段(从末尾到最后一个/的部分),现有拆分重组的实现确实冗余,以下是几种更简洁高效的优化方案:

方案一:直接使用LastIndexOf定位截取

这是最直接轻量的实现,通过从字符串末尾查找分隔符位置,直接截取目标部分:

string path = "LivingOrganism/Animal/Bird/Chicken.exe";
public void SomeFunc()
{
    int lastSeparatorPos = path.LastIndexOf('/');
    if (lastSeparatorPos != -1)
    {
        // 截取从开头到最后一个 '/'(包含该符号)的部分
        path = path.Substring(0, lastSeparatorPos + 1);
    }
    else
    {
        // 无分隔符时清空字符串
        path = string.Empty;
    }
    print("results: " + path);
}

方案二:用Path类处理路径场景

如果你的字符串是文件/目录路径,推荐使用System.IO.Path类的方法,它会自动处理路径分隔符,更贴合路径操作的场景:

using System.IO;

string path = "LivingOrganism/Animal/Bird/Chicken.exe";
public void SomeFunc()
{
    string parentDir = Path.GetDirectoryName(path);
    path = string.IsNullOrEmpty(parentDir) ? string.Empty : parentDir + "/";
    print("results: " + path);
}

Path.GetDirectoryName会直接返回去掉最后一段的父路径,再补回末尾的/即可和原逻辑输出一致。

方案三:极简三元表达式写法

如果追求代码简洁,可以把逻辑压缩为一行:

string path = "LivingOrganism/Animal/Bird/Chicken.exe";
public void SomeFunc()
{
    int lastSlash = path.LastIndexOf('/');
    path = lastSlash != -1 ? path.Substring(0, lastSlash + 1) : string.Empty;
    print("results: " + path);
}

优化优势

原实现需要拆分整个字符串为数组、循环拼接,不仅代码冗余,长字符串场景下效率更低;优化后的方案只需要一次分隔符查找和截取操作,时间复杂度更低,代码逻辑更清晰易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 17:55:11