2 votes

Remplacer les caractères d'une chaîne de caractères en c#

J'ai une chaîne de caractères d'une ou deux phrases (plus d'un mot). Dans cette phrase, il y aura un mot marqué d'une étiquette de hachage, par exemple #word . Il convient de le remplacer par *word* .

Si la phrase est :

Today the weather is very nice #sun

Il devrait devenir :

Today the weather is very nice *sun*

Comment procéder ?

8voto

p.s.w.g Points 81433

Vous pouvez utiliser une expression régulière, comme ceci :

var output = Regex.Replace(input, @"#(\w+)", "*$1*");

1voto

mck Points 920

Vous pouvez essayer ceci

 string text = "Today the weather is very nice #sun";

 int startindex = text.Indexof('#'); 

 int endindex = text.IndexOf(" ", startIndex);

 text = text.Replace(text.substring(startIndex, 1), "*")
 text = text.Replace(text.substring(endindex, 1), "*")

0voto

rhughes Points 3325

Essayez ceci :

string theTag = "sun";
string theWord = "sun";

string tag = String.Format("#{0}", theTag);
string word = String.Format("*{0}*", theWord);

string myString = "Today the weather is very nice #sun";
myString = myString.Replace(tag, word);

0voto

CodeCamper Points 833

Pas de fonctions ou de bibliothèques fantaisistes, juste du bon sens et la solution à votre problème. Il prend en charge autant de mots hachés que vous le souhaitez.

Pour démontrer comment cela fonctionne, j'ai créé 1 TextBox et 1 Button dans un formulaire c# mais vous pouvez utiliser ce code dans une console ou à peu près n'importe quoi.

      string output = ""; bool hash = false;
        foreach (char y in textBox1.Text)
        {
            if(!hash) //checks if 'hash' mode activated
            if (y != '#') output += y; //if not # proceed as normal
            else { output += '*'; hash = true; } //replaces # with *
            else if (y != ' ') output += y; // when hash mode activated check for space
            else { output += "* "; hash = false; } // add a * before the space
        } if (hash) output += '*'; // this is needed in case the hashed word ends the sentence
        MessageBox.Show(output);

et voici

Today the weather is very nice #sun 

devient

Today the weather is very nice *sun*

Voici le même code, mais sous forme de méthode, pour que vous puissiez l'insérer directement dans votre code

   public string HashToAst(string sentence)
    {
        string output = ""; bool hash = false;
        foreach (char y in sentence)
        {
            if (!hash)
                if (y != '#') output += y;
                else { output += '*'; hash = true; } // you can change the # to anything you like here
            else if (y != ' ') output += y;
            else { output += "* "; hash = false; } // you can change the * to something else if you want
        } if (hash) output += '*';                 // and here also
        return output;
    }

Voici une version personnalisable pour montrer comment vous pourriez la modifier

    public string BlankToBlank(string sentence,char search,char highlight)
    {
        string output = ""; bool hash = false;
        foreach (char y in sentence)
        {
            if (!hash)
                if (y != search) output += y;
                else { output += highlight; hash = true; }
            else if (y != ' ') output += y;
            else { output += highlight+" "; hash = false; }
        } if (hash) output += highlight;
        return output;
    }

Ainsi, la recherche portera sur le caractère précédant le mot et le caractère de surbrillance entourera le mot. Le mot est défini comme un caractère jusqu'à ce qu'il atteigne un espace ou la fin de la chaîne.

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X