Posted on by Kalkicode
Code String

Find and replace given pattern by given character

Here given code implementation process.

// C Program
// Find and replace given pattern by given character
#include <stdio.h>

void replace(char str[],char pattern[],int s1 ,int s2 ,char key)
{
  if(s1 < 1 || s2 < 1 || s2 > s1) 
  {
    //When get some invalid data
    return;
  }
  printf("String  : %s\n",str);

  printf("Pattern : %s \nReplace By Character [%c]\n",pattern,key);

  int status = 0;

  int x=0;

  for (int i = 0; i < s1;  i++)
  {
  
    status=0;

    if(pattern[0]==str[i])
    {
      //Initial, assume that  pattern are exist
      status=1;

      if(i+(s2-1) < s1)
      {
        for (int j = 1 ; j < s2 && status==1 ; ++j)
        {
          if(str[i+j] != pattern[j])
          {
            //When pattern are not exist
            status=0;
          }
        }
      }
      else
      {
        status=0;
       }
    }
    if(status==1)
    {
      //When need to replace by key
      
      str[x]=key;
      
      //i are incremented by pattern size
      i+=s2-1;
      
    }
    else
    {
      //In case no need to modified character
      str[x]=str[i];
    }
    //Modify the value of index location
    x++;
  }
  //Assign the remaining characters to space characters
  for (int i = x; i < s1; ++i)
  {
    str[i]=' ';
  }
}


int main()
{
  int s1=0,s2=0;
 
  char str1[]="HIBITHIHIGAMEHIINHICODE";

  char pattern1[] = "HI";

  char key='$';

  //Get the size of str
  s1=sizeof(str1)/sizeof(str1[0])-1;

  s2=sizeof(pattern1)/sizeof(pattern1[0])-1;

  
  replace(str1,pattern1,s1,s2,key);  

  printf("Result : %s\n\n",str1);

  //Test case 2

  char str2[]="MYBOBCSITBOBCDOGXOBC";

  char pattern2[] = "OBC";

  key = '@';

  //Get the size of str
  s1=sizeof(str2)/sizeof(str2[0])-1;

  s2=sizeof(pattern2)/sizeof(pattern2[0])-1;


  replace(str2,pattern2,s1,s2,key);  

  printf("Result : %s\n\n",str2);
  return 0;
}

Output

String  : HIBITHIHIGAMEHIINHICODE
Pattern : HI
Replace By Character [$]
Result : $BIT$$GAME$IN$CODE

String  : MYBOBCSITBOBCDOGXOBC
Pattern : OBC
Replace By Character [@]
Result : MYB@SITB@DOGX@
// Java program
// Find and replace given pattern by given character

public class MyString {

  public String replace(String str, String pattern, char key) {
    
    //get the size
    int s1 = str.length() ;
    int s2 = pattern.length();
    
    if (s1 < 1 || s2 < 1 || s2 > s1) 
    {
      //When get some invalid data
      return str;
    }
    System.out.print("String  : "+str);
    System.out.print("\nPattern : "+pattern);
    System.out.print("\nReplace By Character ["+key+"]\n");
   
    boolean status = false;
    String result = "";
    int x = 0;

    for (int i = 0; i < s1; i++) 
    {
      status = false;

      if (pattern.charAt(0) == str.charAt(i)) 
      {
        //Initial, assume that  pattern are exist
        status = true;
        if (i + (s2 - 1) < s1) 
        {
          for (int j = 1; j < s2 && status == true; ++j) 
          {
            if (str.charAt(i + j) != pattern.charAt(j)) 
            {
              //When pattern are not exist
              status = false;
            }
          }
        }
        else 
        {
          status = false;
        }
      }
      if (status == true) 
      {
        //When need to replace by key
        result += key;
        //i are incremented by pattern size
        i += s2 - 1;
      } 
      else 
      {
        //In case no need to modified character
        result += str.charAt(i);
      }
      //Modify the value of index location
      x++;
    }

    return result;
  }
  public static void main(String[] args) 
  {

    MyString obj = new MyString();
    
    String text = "HIBITHIHIGAMEHIINHICODE";
    
    String pattern ="HI";
    
    char key ='$';
    
    text =  obj.replace(text,pattern,key);

    System.out.print("Result : "+text+"\n\n");

    text = "MYBOBCSITBOBCDOGXOBC" ;

    pattern ="OBC";
    
    key ='@';

    text =  obj.replace(text,pattern,key);
    
    System.out.print("Result : "+text+"\n\n");
  }
}

Output

String  : HIBITHIHIGAMEHIINHICODE
Pattern : HI
Replace By Character [$]
Result : $BIT$$GAME$IN$CODE

String  : MYBOBCSITBOBCDOGXOBC
Pattern : OBC
Replace By Character [@]
Result : MYB@SITB@DOGX@
// C++ program
// Find and replace given pattern by given character
#include<iostream>

using namespace std;
class MyString {
	public:
		string replace(string str, string pattern, char key) {
			//get the size
			int s1 = str.size();
			int s2 = pattern.size();
			if (s1 < 1 ||
				s2 < 1 ||
				s2 > s1) {
				return
				//When get some invalid data
				str;
			}
			cout << "String : " << str;
			cout << "\nPattern : " << pattern;
			cout << "\nReplace By Character [" << key << "]\n";
			bool status = false;
			string result = "";
			int x = 0;
			for (int i = 0; i < s1; i++) {
				status = false;
				if (pattern[0] == str[i]) {
					//Initial, assume that  pattern are exist
					status = true;
					if (i + (s2 - 1) < s1) {
						for (int j = 1; j < s2 &&
							status == true; ++j) {
							if (str[i + j] != pattern[j]) {
								//When pattern are not exist
								status = false;
							}
						}
					} else {
						status = false;
					}
				}
				if (status == true) {
					//When need to replace by key
					result += key;
					//i are incremented by pattern size
					i += s2 - 1;
				} else {
					//In case no need to modified character
					result += str[i];
				}
				//Modify the value of index location
				x++;
			}
			return result;
		}
};
int main() {
	MyString obj =  MyString();
	string text = "HIBITHIHIGAMEHIINHICODE";
	string pattern = "HI";
	char key = '$';
	text = obj.replace(text, pattern, key);
	cout << "Result : " << text << "\n\n";
	text = "MYBOBCSITBOBCDOGXOBC";
	pattern = "OBC";
	key = '@';
	text = obj.replace(text, pattern, key);
	cout << "Result : " << text << "\n\n";
	return 0;
}

Output

String : HIBITHIHIGAMEHIINHICODE
Pattern : HI
Replace By Character [$]
Result : $BIT$$GAME$IN$CODE

String : MYBOBCSITBOBCDOGXOBC
Pattern : OBC
Replace By Character [@]
Result : MYB@SITB@DOGX@
// C# program
// Find and replace given pattern by given character
using System;
public class MyString {
	public String replace(String str, String pattern, char key) {
		//get the size
		int s1 = str.Length;
		int s2 = pattern.Length;
		if (s1 < 1 ||
			s2 < 1 ||
			s2 > s1) {
			return str;
		}
		Console.Write("String : " + str);
		Console.Write("\nPattern : " + pattern);
		Console.Write("\nReplace By Character [" + key + "]\n");
		Boolean status = false;
		String result = "";
		int x = 0;
		for (int i = 0; i < s1; i++) {
			status = false;
			if (pattern[0] == str[i]) {
				//Initial, assume that  pattern are exist
				status = true;
				if (i + (s2 - 1) < s1) {
					for (int j = 1; j < s2 &&
						status == true; ++j) {
						if (str[i + j] != pattern[j]) {
							//When pattern are not exist
							status = false;
						}
					}
				} else {
					status = false;
				}
			}
			if (status == true) {
				//When need to replace by key
				result += key;
				//i are incremented by pattern size
				i += s2 - 1;
			} else {
				//In case no need to modified character
				result += str[i];
			}
			//Modify the value of index location
			x++;
		}
		return result;
	}
	public static void Main(String[] args) {
		MyString obj = new MyString();
		String text = "HIBITHIHIGAMEHIINHICODE";
		String pattern = "HI";
		char key = '$';
		text = obj.replace(text, pattern, key);
		Console.Write("Result : " + text + "\n\n");
		text = "MYBOBCSITBOBCDOGXOBC";
		pattern = "OBC";
		key = '@';
		text = obj.replace(text, pattern, key);
		Console.Write("Result : " + text + "\n\n");
	}
}

Output

String : HIBITHIHIGAMEHIINHICODE
Pattern : HI
Replace By Character [$]
Result : $BIT$$GAME$IN$CODE

String : MYBOBCSITBOBCDOGXOBC
Pattern : OBC
Replace By Character [@]
Result : MYB@SITB@DOGX@
<?php
// Php program
// Find and replace given pattern by given character
class MyString {
	public 	function replace($str, $pattern, $key) {
		//get the size
		$s1 = strlen($str);
		$s2 = strlen($pattern);
		if ($s1 < 1 ||
			$s2 < 1 ||
			$s2 > $s1) {
			return $str;
		}
		echo("String : ". $str);
		echo("\nPattern : ". $pattern);
		echo("\nReplace By Character [". $key ."]\n");
		$status = false;
		$result = "";
		$x = 0;
		for ($i = 0; $i < $s1; $i++) {
			$status = false;
			if ($pattern[0] == $str[$i]) {
				//Initial, assume that  pattern are exist
				$status = true;
				if ($i + ($s2 - 1) < $s1) {
					for ($j = 1; $j < $s2 &&
						$status == true; ++$j) {
						if ($str[$i + $j] != $pattern[$j]) {
							//When pattern are not exist
							$status = false;
						}
					}
				} else {
					$status = false;
				}
			}
			if ($status == true) {
				//When need to replace by key
				$result .= $key;
				//i are incremented by pattern size
				$i += $s2 - 1;
			} else {
				//In case no need to modified character
				$result .= $str[$i];
			}
			//Modify the value of index location
			$x++;
		}
		return $result;
	}
}

function main() {
	$obj = new MyString();
	$text = "HIBITHIHIGAMEHIINHICODE";
	$pattern = "HI";
	$key = '$';
	$text = $obj->replace($text, $pattern, $key);
	echo("Result : ". $text ."\n\n");
	$text = "MYBOBCSITBOBCDOGXOBC";
	$pattern = "OBC";
	$key = '@';
	$text = $obj->replace($text, $pattern, $key);
	echo("Result : ". $text ."\n\n");

}
main();

Output

String : HIBITHIHIGAMEHIINHICODE
Pattern : HI
Replace By Character [$]
Result : $BIT$$GAME$IN$CODE

String : MYBOBCSITBOBCDOGXOBC
Pattern : OBC
Replace By Character [@]
Result : MYB@SITB@DOGX@
// Node Js program
// Find and replace given pattern by given character
class MyString {
	replace(str, pattern, key) {
		//get the size
		var s1 = str.length;
		var s2 = pattern.length;
		if (s1 < 1 ||
			s2 < 1 ||
			s2 > s1) {
			return str;
		}

		process.stdout.write("String : " + str);
		process.stdout.write("\nPattern : " + pattern);
		process.stdout.write("\nReplace By Character [" + key + "]\n");
		var status = false;
		var result = "";
		var x = 0;
		for (var i = 0; i < s1; i++) {
			status = false;
			if (pattern[0] == str[i]) {
				//Initial, assume that  pattern are exist
				status = true;
				if (i + (s2 - 1) < s1) {
					for (var j = 1; j < s2 &&
						status == true; ++j) {
						if (str[i + j] != pattern[j]) {
							//When pattern are not exist
							status = false;
						}
					}
				} else {
					status = false;
				}
			}

			if (status == true) {
				//When need to replace by key
				result += key;
				//i are incremented by pattern size
				i += s2 - 1;
			} else {
				//In case no need to modified character
				result += str[i];
			}

			//Modify the value of index location
			x++;
		}

		return result;
	}
}

function main(args) {
	var obj = new MyString();
	var text = "HIBITHIHIGAMEHIINHICODE";
	var pattern = "HI";
	var key = '$';
	text = obj.replace(text, pattern, key);
	process.stdout.write("Result : " + text + "\n\n");
	text = "MYBOBCSITBOBCDOGXOBC";
	pattern = "OBC";
	key = '@';
	text = obj.replace(text, pattern, key);
	process.stdout.write("Result : " + text + "\n\n");
}

main();

Output

String : HIBITHIHIGAMEHIINHICODE
Pattern : HI
Replace By Character [$]
Result : $BIT$$GAME$IN$CODE

String : MYBOBCSITBOBCDOGXOBC
Pattern : OBC
Replace By Character [@]
Result : MYB@SITB@DOGX@
#  Python 3 program
#  Find and replace given pattern by given character
class MyString :
	def replace(self, str, pattern, key) :
		s1 = len(str)
		s2 = len(pattern)
		if (s1 < 1 or s2 < 1 or s2 > s1) :
			return str
		
		print("String : ", str, end = "")
		print("\nPattern : ", pattern, end = "")
		print("\nReplace By Character [", key ,"]\n", end = "")
		status = False
		result = ""
		x = 0
		i = 0
		while (i < s1) :
			status = False
			if (pattern[0] == str[i]) :
				# Initial, assume that  pattern are exist
				status = True
				if (i + (s2 - 1) < s1) :
					j = 1
					while (j < s2 and status == True) :
						if (str[i + j] != pattern[j]) :
							# When pattern are not exist
							status = False
						
						j += 1
					
				else :
					status = False
				
			
			if (status == True) :
				# When need to replace by key
				result += key
				# i are incremented by pattern size
				i += s2 - 1
			else :
				# In case no need to modified character
				result += str[i]
			
			# Modify the value of index location
			x += 1
			i += 1
		
		return result
	

def main() :
	obj = MyString()
	text = "HIBITHIHIGAMEHIINHICODE"
	pattern = "HI"
	key = '$'
	text = obj.replace(text, pattern, key)
	print("Result : ", text ,"\n\n", end = "")
	text = "MYBOBCSITBOBCDOGXOBC"
	pattern = "OBC"
	key = '@'
	text = obj.replace(text, pattern, key)
	print("Result : ", text ,"\n\n", end = "")


if __name__ == "__main__":
	main()

Output

String :  HIBITHIHIGAMEHIINHICODE
Pattern :  HI
Replace By Character [ $ ]
Result :  $BIT$$GAME$IN$CODE

String :  MYBOBCSITBOBCDOGXOBC
Pattern :  OBC
Replace By Character [ @ ]
Result :  MYB@SITB@DOGX@
#  Ruby program
#  Find and replace given pattern by given character
class MyString 
	def replace(str, pattern, key) 
		s1 = str.length()
		s2 = pattern.length()
		if (s1 < 1 ||
			s2 < 1 ||
			s2 > s1) 
			return str
		end
		print("String  :", str)
		print("\nPattern  :", pattern)
		print("\nReplace By Character [", key ,"]\n")
		status = false
		result = ""
		x = 0
		i = 0
		while (i < s1) 
			status = false
			if (pattern[0] == str[i]) 
				# Initial, assume that  pattern are exist
				status = true
				if (i + (s2 - 1) < s1) 
					j = 1
					while (j < s2 &&
						status == true) 
						if (str[i + j] != pattern[j]) 
							# When pattern are not exist
							status = false
						end
						j += 1
					end
				else 
					status = false
				end
			end
			if (status == true) 
				# When need to replace by key
				result += key
				# i are incremented by pattern size
				i += s2 - 1
			else 
				# In case no need to modified character
				result += str[i]
			end
			# Modify the value of index location
			x += 1
			i += 1
		end
		return result
	end
end
def main() 
	obj = MyString.new()
	text = "HIBITHIHIGAMEHIINHICODE"
	pattern = "HI"
	key = '$'
	text = obj.replace(text, pattern, key)
	print("Result  :", text ,"\n\n")
	text = "MYBOBCSITBOBCDOGXOBC"
	pattern = "OBC"
	key = '@'
	text = obj.replace(text, pattern, key)
	print("Result  :", text ,"\n\n")
end
main()

Output

String  :HIBITHIHIGAMEHIINHICODE
Pattern  :HI
Replace By Character [$]
Result  :$BIT$$GAME$IN$CODE

String  :MYBOBCSITBOBCDOGXOBC
Pattern  :OBC
Replace By Character [@]
Result  :MYB@SITB@DOGX@

// Scala program
// Find and replace given pattern by given character
class MyString {
	def replace(str: String, pattern: String, key: Char): String = {
		var s1: Int = str.length();
		var s2: Int = pattern.length();

		if (s1 < 1 ||
			s2 < 1 ||
			s2 > s1) {
			return str;
		}
		print("String : " + str);
		print("\nPattern : " + pattern);
		print("\nReplace By Character [" + key + "]\n");
		var status: Boolean = false;
		var result: String = "";
		var x: Int = 0;
		var i: Int = 0;
		while (i < s1) {
			status = false;

			if (pattern(0) == str(i)) {
				//Initial, assume that  pattern are exist
				status = true;

				if (i + (s2 - 1) < s1) {
					var j: Int = 1;
					while (j < s2 &&
						status == true) {
						if (str(i + j) != pattern(j)) {
							//When pattern are not exist
							status = false;
						}
						j += 1;
					}
				} else {
					status = false;
				}
			}
			if (status == true) {
				//When need to replace by key
				result += key;

				//i are incremented by pattern size
				i += s2 - 1;
			} else {
				//In case no need to modified character
				result += str(i);
			}
			//Modify the value of index location
			x += 1;
			i += 1;
		}
		return result;
	}
}
object Main {
	def main(args: Array[String]): Unit = {
		var obj: MyString = new MyString();
		var text: String = "HIBITHIHIGAMEHIINHICODE";
		var pattern: String = "HI";
		var key: Char = '$';
		text = obj.replace(text, pattern, key);
		print("Result : " + text + "\n\n");
		text = "MYBOBCSITBOBCDOGXOBC";
		pattern = "OBC";
		key = '@';
		text = obj.replace(text, pattern, key);
		print("Result : " + text + "\n\n");
	}
}

Output

String : HIBITHIHIGAMEHIINHICODE
Pattern : HI
Replace By Character [$]
Result : $BIT$$GAME$IN$CODE

String : MYBOBCSITBOBCDOGXOBC
Pattern : OBC
Replace By Character [@]
Result : MYB@SITB@DOGX@
// Swift program
// Find and replace given pattern by given character
class MyString {
	func replace(_ text: String, _ pt: String, _ key: Character) -> String {
      	var str = Array(text);
      	var pattern = Array(pt);
		let s1: Int = str.count;
		let s2: Int = pattern.count;
		if (s1 < 1 ||
			s2 < 1 ||
			s2 > s1) {
			return text;
		}
		print("String : ", text, terminator: "");
      	print("\nPattern : ", pt, terminator: "");
      	print("\nReplace By Character [", key ,"]\n", terminator: "");
		var status: Bool = false;
		var result: String = "";
		var x: Int = 0;
		var i: Int = 0;
		while (i < s1) {
			status = false;
			if (pattern[0] == str[i]) {
				//Initial, assume that  pattern are exist
				status = true;
				if (i + (s2 - 1) < s1) {
					var j: Int = 1;
					while (j < s2 &&
						status == true) {
						if (str[i + j] != pattern[j]) {
							//When pattern are not exist
							status = false;
						}
						j += 1;
					}
				} else {
					status = false;
				}
			}
			if (status == true) {
				//When need to replace by key
				result += String(key);
				//i are incremented by pattern size
				i += s2 - 1;
			} else {
				//In case no need to modified character
				result += String(str[i]);
			}
			//Modify the value of index location
			x += 1;
			i += 1;
		}
		return result;
	}
}
func main() {
	let obj: MyString = MyString();
	var text: String = "HIBITHIHIGAMEHIINHICODE";
	var pattern: String = "HI";
	var key: Character = "$";
	text = obj.replace(text, pattern, key);
	print("Result : ", text ,"\n\n", terminator: "");
	text = "MYBOBCSITBOBCDOGXOBC";
	pattern = "OBC";
	key = "@";
	text = obj.replace(text, pattern, key);
	print("Result : ", text ,"\n\n", terminator: "");
}
main();

Output

String :  HIBITHIHIGAMEHIINHICODE
Pattern :  HI
Replace By Character [ $ ]
Result :  $BIT$$GAME$IN$CODE

String :  MYBOBCSITBOBCDOGXOBC
Pattern :  OBC
Replace By Character [ @ ]
Result :  MYB@SITB@DOGX@

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment