简体   繁体   中英

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

I have some string and I would like to replace the last .something with a new string. As example:

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

So it doesn't matter how many ..... there are, I'd like to change only the last one and the string what after the last . is coming.

I saw in C# there is Path.ChangeExtension but its only working in a combination with a File - Is there no way to use this with a string only? Do I really need regex?

You can use 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;

of course some checking is required to be sure that LastIndexOf finds the final point.

However, seeing the other answers, let me say that, while Path.ChangeExtension works, it doesn't feel right to me to use a method from a operating system dependent file handling class to manipulate a string. (Of course, if this string is really a filename, then my objection is invalid)

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

Output:

blabla.test.bla.text.new

ChangeExtension should work as advertised;

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;

No you don't need regular expressions for this. Just .LastIndexOf and .Substring will suffice.

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

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

Please use this function.

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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