Home > Software design >  Replace * in string by character in c#. Example p**gra* replace * by rom the output will be program
Replace * in string by character in c#. Example p**gra* replace * by rom the output will be program

Time:07-15

This is the code I'll try. But I got wrong output. Replace * in string by character in c#. Example p**gra* replace * by rom the output will be program.

namespace Uncensor
{
    class Program
    {

        // "*h*s *s v*ry *tr*ng*", "Tiiesae" ➜ "This is very strange"
        static string uncensor(string str,string s)
        {
            string s1 = "";
            int i, j;
            if (str.Contains("*"))
            {
               
               for (i = 0; i < str.Length; i  )
               {
                    if (str[i] == '*')
                    {
                        for (j = 0; j < s.Length; j  )
                    {
                        
                            s1 = str.Replace(str[i], s[j]);
                        }
                    }
               }

                return s1;
            }
            else
            {
                return str;
            }
            
        }
        static void Main(string[] args)
        {
            Console.WriteLine("Enter  string:");
            string str = Console.ReadLine();
            Console.WriteLine("Enter string to be replaced by * :");
            string s = Console.ReadLine();

           string original_text= uncensor(str, s);
            Console.WriteLine(original_text);

            Console.Read();
        }
    }
}

CodePudding user response:

This is easy with linq:

string a = "*h*s *s v*ry *tr*ng*";
string b = "Tiiesae";

int index = 0;
string c = new string(a.Select(x => x == '*' ? b[index  ] : x).ToArray());

CodePudding user response:

using System;
using System.Text;
                    
public class Program
{
    public static void Main()
    {
        Console.WriteLine("Enter  string:");
        string str ="*h*s *s v*ry *tr*ng*";
        Console.WriteLine("Enter string to be replaced by * :");
        string s ="Tiiesae";

       string original_text= uncensor(str, s);
        Console.WriteLine(original_text);
    }
    static string uncensor(string str,string s)
    {
        StringBuilder sb=new StringBuilder();
        int i, j=0;
        if (str.Contains("*"))
        {
           for ( i = 0; i < str.Length; i  )
           {
                if (str[i] == '*')
                {
                    sb.Append(s[j]);
                    j  ;
                }
               else
               sb.Append(str[i]);
           }

            return sb.ToString();
        }
        else
        {
            return str;
        }
        
    }
}
  •  Tags:  
  • c#
  • Related