문제

I have a program that reads from a xml document. In this xml document some of the attributes contain special characters like "\n", "\t", etc.

Is there an easy way to replace all of these strings with the actual character or do I just have to do it manually for each character like the following example?

Manual example:

s.Replace("\\n", "\n").Replace("\\t", "\t")...

edit:

I'm looking for some way to treat the string like an escaped string like this(even though I know this doesn't work)

s.Replace("\\", "\");
도움이 되었습니까?

다른 팁

Why not just walk the document and build up the new string in one pass. Saves a lot of duplicate searching and intermediate allocations

string ConvertSpecialCharacters(string input) {
  var builder = new StringBuilder();
  bool inEscape = false;
  for (int i = 0; i < input.Length ; i++) {
    if (inEscape) {
     switch (input[i]) {
      case 'n':  
        builder.Append('\t');
        break;
      case 't':
        builder.Append('\n');
        break;
      default:
        builder.Append('\\');
        builder.Append(input[i]);
    }
    else if (input[i] == '\\' && i + 1 < input.Length) {
      inEscape = true;
    }
    else {
      builder.Append(input[i]);
    } 
  }
  return builder.ToString();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top