C# How to replace empty string with value

Sudip Bhatt 2,281 Reputation points
2020-12-17T11:19:21.263+00:00

oldGroupKey = item.Element("GroupKey").Value;
oldGroupKey = oldGroupKey.Replace((string.IsNullOrEmpty(oldGroupKey.Split('~')[2]) ? "0" : oldGroupKey.Split('~')[2]), d.XFundCode);

after executing first line OldGroupKey value look like

Segment Details~Anixter~~NBM~~1~HQ

after Anixter ~~

i have to insert a value inside ~~

string.replace not being able to replace empty string with value because there is no value inside ~~

so tell me how could i replace empty string with value. thanks

Developer technologies Windows Forms
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2020-12-17T11:29:57.317+00:00

    Check if this example works with empty and non-empty segments:

    string old_string = "Segment Details~Anixter~~NBM~~1~HQ";
    int position = 2;
    string new_value = "SomeCode";
    
    var a = old_string.Split( '~' );
    
    string new_string = string.Join( "~", a.Take( position ).Append( new_value ).Concat( a.Skip( position + 1 ) ) );
    
    Console.WriteLine( old_string );
    Console.WriteLine( new_string );
    

1 additional answer

Sort by: Most helpful
  1. Kyle Wang 5,531 Reputation points Microsoft External Staff
    2020-12-18T06:13:36.037+00:00

    Did you want to insert a substring inside the first "~~"?

    If so, you can call IndexOf(String) to get the index of "~~". By +1, you can get the index of the second ‘~’.

    int index = teststr.IndexOf("~~") + 1;  
    

    Then you can call String.Substring Method and operator + to get new string.

    string newstr = teststr.Substring(0, index) + "newvalue" + teststr.Substring(index, teststr.Length - index);  
    //  Segment Details~Anixter~newvalue~NBM~~1~HQ  
    
    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.