简体   繁体   English

更改“/”分隔字符串中最后一个元素的最有效方法是什么

[英]What's the most efficient way to change the last element in a '/' delimited string

I have a string object in c# with a bunch of elements delimited by '/' characters. 我在c#中有一个字符串对象,其中包含一些由'/'字符分隔的元素。 The string will look something like this: 字符串看起来像这样:

"element1/element2/element3/element4" “部件1 / element2的/元素3 /元素4”

What's the most efficient way to change the last element in the '/' delimited string? 更改'/'分隔字符串中最后一个元素的最有效方法是什么?

Use string.LastIndexOf : 使用string.LastIndexOf

string s = "element1/element2/element3/element4";
s = s.Substring(0, s.LastIndexOf('/') + 1) + "foo";

如果这是文件名/路径字符串,则应使用System.IO.Path

is there a 'lastIndexOf' in the C# String class? C#String类中有'lastIndexOf'吗? ( I don't code in C# normally ), if it exists you could use that to get a reference to the last / in the string, and that / precedes the last element of your string. (我通常不用C#编写代码),如果它存在,你可以使用它来获取对字符串中最后一个/的引用,并且/在字符串的最后一个元素之前。

Like Joel suggests.. maybe something like this: 像乔尔建议......可能是这样的:

     string path = (System.IO.Path.GetDirectoryName(@"element1/element2/element3/element4") +
        System.IO.Path.DirectorySeparatorChar + "foo");
     string new_path = path.Replace(System.IO.Path.DirectorySeparatorChar, '/');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM