简体   繁体   中英

Replace string before dot with another string

I am having a string like below :

String str = "abc.History_logs";

Now I want to replace string before dot with this fixed string : apc

So final string will be like this :

apc.History_logs;

Code :

String str = "abc.History_logs";
string final = string.Join('apc.',str.Substring(str.IndexOf(".") + 1).Trim()); //error:invalid arguments for join

You can simply use string.Concat

string final = string.Concat("apc.", str.Substring(str.IndexOf(".") + 1).Trim());

I don't think there is an overloaded method exists for String.Join(String, String)

您可以使用此正则表达式

Regex.Replace(str,@".*?\.","apc.")

此Regex模式将忽略点本身,从而使您可以替换所需的任何内容而不必记住重新插入点:

Regex.Replace(str, @".*?(?=\.)", "apc");

string.Replace method looks more suitable for this

    string source = "abc.d";
    string target = "apc";
    source = source.Replace(source.Split('.')[0], target);

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