我有一个实际的函数,用字符串中的其他特定字符替换特定的字符。 它工作正常,但我觉得这个功能很难看。如何通过更优雅的功能替换此功能?
private string CorrectString(string data)
{
string retData = string.Empty;
for (int j = 0; j < data.Length; j++)
{
char myChar = data[j];
switch (myChar)
{
case 'à':
myChar = '@';
break;
case 'ç':
myChar = '\\';
break;
case '[':
myChar = '°';
break;
case '!':
myChar = '!';
break;
case 'é':
myChar = '{';
break;
case 'è':
myChar = '}';
break;
case ']':
myChar = '§';
break;
case '¦':
myChar = 'ù';
break;
case '`':
myChar = 'µ';
break;
case '#':
myChar = '£';
break;
case '@':
myChar = 'à';
break;
case '°':
myChar = '[';
break;
case '¤':
myChar = '€';
break;
case 'µ':
myChar = '`';
break;
case '~':
myChar = '"';
break;
case 'Ý':
myChar = 'Ý';
break;
case '¢':
myChar = '¢';
break;
case '£':
myChar = '#';
break;
case '§':
myChar = ']';
break;
case '¬':
myChar = '¬';
break;
case '|':
myChar = '|';
break;
case '"':
myChar = '~';
break;
case '{':
myChar = 'é';
break;
case '}':
myChar = 'è';
break;
case 'ù':
myChar = '¦';
break;
case '\\':
myChar = 'ç';
break;
}
retData = retData.Insert(j, myChar.ToString());
}
return retData;
}
答案 0 :(得分:4)
解决方案1
您只需将字符保存在两个字符串中即可:
var toTranslate = "àç[!é...";
var translateTo = @"@\°...";
然后在找到字符时进行翻译:
int index = toTranslate.IndexOf(myChar);
if (index > -1)
{
myChar = translateTo[index];
}
解决方案2
另一种有效但不太可读的方法是存储Dictionary<char, char>
并像这样使用它:
myDictionary['à'] = '@';
myDictionary['ç'] = '\\';
...
if (myDictionary.Keys.Contains(myChar))
{
myChar = myDictionary[myChar];
}
答案 1 :(得分:1)
如果不考虑速度,您可能需要创建Dictionary<char, char>
并为字典的每个键检查它是否等于当前字符。如果是,则用适当的值替换它。推进一个角色并继续。
答案 2 :(得分:0)
或一系列替换语句:
myCleanString= Regex.Replace(data, "à", @"@")
.Replace("ç", "\\")
.Replace("[", "°") ...
答案 3 :(得分:0)
_MyString1 = "@\\°!"; // those you put in the partial class or public class of your program
_MyString1 = "@\\°!";
string c = _MyString1.Substring(_MyString.IndexOf("à"),1);