Search the given substring in a string and replace it by new substring:
The substring is a string within another string. Here, the program is written to check whether a substring is present in a string or not, if it is present then the number of times it occurs in the string i.e. the frequency of the substring and if it is present, then replace the substring with another given string.
For example, if the given string is: I are a good girl.
Now, I want to search the substring ‘are’ in the input string. It is presently one time in the string. Now, the new given substring is ‘am’. So the substring ‘are’ will be replaced by the substring ‘am’.
So, the frequency of the substring will be 1. And the string after replacing the substring will be:
“I am a good girl”.
INPUT: A string and two substrings (one substring is to be replaced and to find the frequency and another substring with which the previously given substring is to be replaced)
.
OUTPUT: The frequency of the searched substring and the new string after replacing with the new substring.
PROCESS:
Step 1: [taking the inputs]
Read str [the main string]
Read sub [the substring to be searched and replaced]
Read str1 [the new substring]
Step 2: [Searching and replacing the substring]
Set c<-0
[calculating the lengths of the strings]
Set len<-length of ‘str’
Set sub_len<-length of ‘sub’
Set r_len<-length of ‘str1’
[loop to replace the string]
For i=0 to len-1 repeat
Set f<-0
Set s<-i
[searching if the substring is present or not]
Set j<-0
While str[i]=sub[j] repeat
If j==sub_len-1 then
Set f<-1
Set c<-c+1
[End of ‘if’]
Set i<-i+1
Set j<-j+1
[End of ‘while’ loop]
Set e<-i
If f=0 then
Set i<-i-j
else
for j=s to e-1 repeat
for k=s to len-1 repeat
Set str[k]<-str[k+1]
[End of ‘for’ loop]
Set len<-len-1
Set i<-i-1
[End of ‘for’ loop]
For j=s to s+r_len-1 repeat
For k=len to j step -1 repeat
Set str[k+1]<-str[k]
Set str[j]<-str1[j-s]
Set len<-len+1
Set i<-i+1
[End of ‘for’ loop]
[End of ‘for’ loop]
[End of ‘for ‘ loop]
[printing the frequency of the character]
Print "The frequency of the substring is c”
[End of counting the frequency]
Step 3: Stop.
The time complexity of this program is O() where ‘n’ is the number of characters of the main string.
The space complexity of this program is O(n) where ‘n’ is the number of characters of the main string.
Related
Contributed by