删除除最后一个字符之外的特定字符
我有一个文本字符串,我想用下划线替换点,除了字符串中找到的最后一个字符。
示例:
input = "video.coffee.example.mp4"
result = "video_coffe_example.mp4"
我有一个代码,但这替换了所有内容,包括最后一个字符
第一个选项失败了
static string replaceForUnderScore(string file)
{
return file = file.Replace(".", "_");
}
我实现了第二个适合我的选项,但我发现它非常广泛并且不是很优化
static string replaceForUnderScore(string file)
{
string result = "";
var splits = file.Split(".");
var extension = splits.LastOrDefault();
splits = splits.Take(splits.Count() - 1).ToArray();
foreach (var strItem in splits)
{
result = result + "_" + strItem;
}
result = result.Substring(1, result.Length-1);
string finalResult = result + "."+extension;
return finalResult;
}
有没有更好的方法来做到这一点?
I have a text string and I want to replace the dots with underscores except for the last character found in the string.
Example:
input = "video.coffee.example.mp4"
result = "video_coffe_example.mp4"
I have a code but this replaces everything including the last character
first option failed
static string replaceForUnderScore(string file)
{
return file = file.Replace(".", "_");
}
I implemented a second option that works for me but I find that it is very extensive and not very optimized
static string replaceForUnderScore(string file)
{
string result = "";
var splits = file.Split(".");
var extension = splits.LastOrDefault();
splits = splits.Take(splits.Count() - 1).ToArray();
foreach (var strItem in splits)
{
result = result + "_" + strItem;
}
result = result.Substring(1, result.Length-1);
string finalResult = result + "."+extension;
return finalResult;
}
Is there a better way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最简单(也可能是最快)的方法就是迭代字符串:
另一种方法是使用 System.IO.Path。这当然是最简洁的:
The simplest (and probably fastest) way is just to iterate over the string:
Another approach would be to use
System.IO.Path
. It's certainly the most succinct:在我的脑海中,但这可能会起作用。
Off the top of my head but this might work.
由于您使用文件,我建议使用 路径类:全部
我们想要的是仅更改文件名,同时保持扩展名不变:
Since you work with files, I suggest using Path class: all
we want is to change file name only while keeping extension intact:
正则表达式将帮助您做到这一点。
添加命名空间
using System.Text.RegularExpressions;
并使用以下代码:
这里我们指定了替换
的最大次数。
输出如下:
此外,您可以更新代码以替换除最后一个点之外的任意数量点。
Regex will help you to do this.
Add the namespace
using System.Text.RegularExpressions;
And use this code:
Here we specified the maximum number of times to replace the
.
The output would be the following:
Additionally, you can update the code to replace any number of dots excluding the last one.
您可以通过断言匹配时右侧仍然存在一个点,将除最后一个点之外的所有点替换为下划线。
结果将是
You can replace all the dots with an underscore except for the last dot by asserting that there is still a dot present to the right when matching one.
The result will be