I Love Stackoverflow
I Love Stackoverflow

Reputation: 6868

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

Upvotes: 0

Views: 594

Answers (4)

Satpal
Satpal

Reputation: 133433

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)

Upvotes: 2

Kira
Kira

Reputation: 1443

string.Replace method looks more suitable for this

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

Upvotes: 2

Abion47
Abion47

Reputation: 24736

This Regex pattern will ignore the dot itself, allowing you to substitute whatever you want without having to remember to reinsert the dot:

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

Upvotes: 2

Sateesh Pagolu
Sateesh Pagolu

Reputation: 9606

You could use this regex

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

Upvotes: 2

Related Questions