C# string replacement , not working

后端 未结 6 1544
悲哀的现实
悲哀的现实 2020-12-07 03:47

I have a string which I read in from :

TextReader tr = new StreamReader(this.dataPath );
string contents = tr.ReadToEnd(); 

The value of co

相关标签:
6条回答
  • 2020-12-07 04:26

    Try

    contents = contents.Replace(xmlString,xmlString + styleSheet );
    

    This is because the String class is immutable.

    0 讨论(0)
  • 2020-12-07 04:28

    The Replace() method returns a new string object, so you'll have to change your code to:

     content = contents.Replace(xmlString,xmlString + styleSheet );
    
    0 讨论(0)
  • 2020-12-07 04:40

    This doesn't really answer your question but that has already been answered more than once so please permit me this aside.

    I've seen many cases where people read the content of a stream into a string so that some really simple manipulation can be done. In many cases and certainly this case the operation can be performed without ever making a copy of the whole string and working on that.

    With a little more effort than your existing code you could write a StreamStringReplace method that takes as its parameters an input stream, an output stream, a find string and a replace string. This would be much more efficient especially if your xml docs can get massive.

    0 讨论(0)
  • 2020-12-07 04:41

    you probably want to do this:

    string styleSheet = "<?xml-stylesheet type=\"text/xsl\" href=\"message.xsl\"?>";
    string xmlString = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
    TextReader tr = new StreamReader(this.dataPath );
    string contents = tr.ReadToEnd(); 
    string result = contents.Replace(xmlString,xmlString + styleSheet );
    

    You're currently not capturing the replace results that you're doing on the last line.

    0 讨论(0)
  • 2020-12-07 04:46

    System.String is immutable. Operations such as Replace return a new string rather than modifying this string. Use System.Text.StringBuilder if you truly need a mutable string or just assign the result of the Replace call to a variable.

    0 讨论(0)
  • 2020-12-07 04:52

    To get technical (and who doesn't love that), if you are searching for the string`

    <?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n.....
    

    The search string would have to be

    "<?xml version=\\\"1.0\\\" encoding=\\\"utf-8\\\"?>\\r\\n"
    

    or

     @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n"
    
    0 讨论(0)
提交回复
热议问题