繁体   English   中英

字符串:替换字符串中的最后一个“ .something”?

[英]String: replace last “.something” in a string?

我有一些字符串,我想用新字符串替换最后的.something。 例如:

string replace = ".new";
blabla.test.bla.text.jpeg => blabla.test.bla.text.new
testfile_this.00001...csv => testfile_this.00001...new

因此,有多少个.....都无所谓,我只想更改最后一个,而在最后一个之后更改字符串. 来了。

我在C#中看到有Path.ChangeExtension,但是它只能与File一起使用-是否没有办法仅将其与字符串一起使用? 我真的需要正则表达式吗?

您可以使用string.LastIndexOf('.');

string replace = ".new"; 
string test = "blabla.test.bla.text.jpeg";
int pos = test.LastIndexOf('.');
if(pos >= 0)
    string newString = test.Substring(0, pos-1) + replace;

当然,需要进行一些检查以确保LastIndexOf找到终点。

但是,看到其他答案,我要说的是,尽管Path.ChangeExtension起作用了,但觉得使用操作系统依赖的文件处理类中的方法来操作字符串对我来说并不正确。 (当然,如果此字符串确实是文件名,那么我的反对意见无效)

string replace = ".new";
string p = "blabla.test.bla.text.jpeg";
Console.WriteLine(Path.GetFileNameWithoutExtension(p) + replace);

输出:

blabla.test.bla.text.new

ChangeExtension应该按照广告中的说明工作;

string replace = ".new";
string file = "testfile_this.00001...csv";

file = Path.ChangeExtension(file, replace);

>> testfile_this.00001...new
string s = "blabla.test.bla.text.jpeg";
s = s.Substring(0, s.LastIndexOf(".")) + replace;

不,您不需要正则表达式。 仅.LastIndexOf和.Substring就足够了。

string replace = ".new";
string input = "blabla.bla.test.jpg";

string output = input.Substring(0, input.LastIndexOf('.')) + replace;
// output = "blabla.bla.test.new"

请使用此功能。

public string ReplaceStirng(string originalSting, string replacedString)
{
    try
    {
        List<string> subString = originalSting.Split('.').ToList();
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < subString.Count - 1; i++)
        {
            stringBuilder.Append(subString[i]);
        }
        stringBuilder.Append(replacedString);
        return stringBuilder.ToString();
    }
    catch (Exception ex)
    {
        if (log.IsErrorEnabled)
            log.Error("[" + System.DateTime.Now.ToString() + "] " + System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + " :: " + System.Reflection.MethodBase.GetCurrentMethod().Name + " :: ", ex);
            throw;
    }
}

暂无
暂无

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

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