Read and edit a specific word in a string (c#)

Asked

Viewed 322 times

0

I have a text file:

https://imgur.com/a/2DKpF

I put this piece of code in a string, and I need to replace the name inside (in the case of Matthew) to another string name.

  • 2

    Have you tried doing anything? The idea of the OS is not to "make the code" but to help find solutions/problems.. https://answall.com/tour

2 answers

0


You can use String.Replace.

Ex:

 public static void Main()
   {
      String s = new String('a', 3);
      Console.WriteLine("The initial string: '{0}'", s);
      s = s.Replace('a', 'b').Replace('b', 'c').Replace('c', 'd');
      Console.WriteLine("The final string: '{0}'", s);
   }

Reference: https://msdn.microsoft.com/pt-br/library/czx8s9ts(v=vs.110). aspx

0

What I understood from your question was: You want to change what’s inside the tags <name>..esse texto aqui..</name> this text belongs to a String

So do the following:

 // adicione a referência
    using System.Xml;

    //carregando o texto que você mencionou em uma string
    String textoXml = "<Farmer><name>nome</name><isEmoting>false</isEmoting><isCharging>false</isCharging></Farmer>";

   // Criando um novo xmlDocument
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.InnerXml = textoXml;// pasando para o Xml o conteúdo da string

    //Pegando o elemento pelo nome da TAG
    XmlNodeList xNodeList = xmlDoc.GetElementsByTagName("name");

    foreach (XmlNode xNode in xNodeList)
    {
       xNode["name"].InnerText = "outroNome";// alterando o texto desejado
    }

    String textoAlterado = xmlDoc.InnerXml; //texto alterado 

The result will be:

<Farmer><name>outroNome</name><isEmoting>false</isEmoting><isCharging>false</isCharging></Farmer>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.