我需要用C#替換一部分字符串。 我只能找到一個類似的問題,關於如何實現這個here,但它是PHP。如何將兩個或多個字符串替換爲對方?
我的情況涉及到詞典[字符串,字符串]持有成對更換,如:
- 狗,貓
- 貓,小鼠,
- 鼠標,猛禽
而且我有一個字符串,其值爲:
"My dog ate a cat which once ate a mouse got eaten by a raptor"
我需要一個函數來得到這樣的:
"My cat ate a mouse which once ate a raptor got eaten by a raptor"
如果我列舉的詞典和順序調用與string.replace,我得到這個:
"My raptor ate a raptor which once ate a raptor got eaten by a raptor"
這很奇怪,如果這還沒有被問過,(這是常識嗎?),但我找不到任何東西。所以我很抱歉,如果有,我錯過了。
這樣做的一個骯髒的方法是使用一些中間文本。因此,將'狗'轉換爲'1','貓'轉換爲'2',然後進行第二次轉換,將'1'和'2'轉換爲您想要的值。確保使用比'1'和'2'更獨特的東西(也許是一個GUID)。就像我說的那樣,它很髒,我相信還有更好的方法。 – xbonez 2012-03-07 11:02:06
字典{「foo」:「1」,「bar」:「2」,「foobar」:「3」}和輸入「foo bar foobarbar」是什麼? – Dogbert 2012-03-07 13:26:56
@Dogbert「1 2 32」 – 2012-03-07 13:30:12