2017-08-30 4 views
-4

2つのパイプまたはエンディングパイプの間の文字列を置き換えるのにC#で問題があります。2つのパイプ間の文字列の置換c#

例:私は前に第二の値

を交換したい:0 | | 2 | 3

置換後:0 | | 2 | 3

どうすればいいですか?値は2桁以上にすることもできます。

もう1つの質問:どのように最初の値を置き換えることができますか?

それは私が「replaceString(文字列テキスト、valueindexToReplace、文字列replacewihtをint型)」のように変更したいと考えている値を選択しdynamiclyあるべき

はあなたの助けをいただき、ありがとうございます。

+5

利用のstring.Splitとstring.join? – Derek

+1

何か試しましたか? – Maritim

答えて

4

この例では、2番目の番号(index = 1)を "4"に置き換えることができます。

string s = "0|1|2|3"; 
var split = s.Split('|'); 
split[1] = "4"; 
string after = string.Join("|", split); 

またはメソッドを持つあなたが示唆したように:

string s = "0|1|2|3"; 
string after = replaceString(s, 1, "4"); 

string replaceString(string text, int valueindexToReplace, string replaceWith) 
{ 
    var split = text.Split('|'); 
    split[valueindexToReplace] = replaceWith; 
    string after = string.Join("|", split); 
    return after; 
} 
2
public string SetInPipe(string pipe, int index, string pipeItem) 
{ 
    var split = pipe.Split('|'); 
    split[index] = pipeItem; 
    return string.Join("|", split); 
} 

例:

var result = SetInPipe("0|1|2|3", 1, "4"); 
関連する問題