Program to Replace a Substring in a String
Manual algorithm plus working code in Python, Java, and C to replace every occurrence of a substring, with Wipro placement context and edge cases.
Replacing a substring in a string is a Wipro campus coding question that tests whether you can implement string traversal without relying on a single built-in call.
The Problem
Three strings arrive as input. s1 is the full source string. s2 is the substring you want to locate. s3 is the text that replaces every occurrence of s2 found inside s1. All characters that are not part of a match are copied unchanged to the output.
Source (s1) | Target (s2) | Replacement (s3) | Output |
|---|---|---|---|
hi hello | hi | hey | hey hello |
banana | an | XX | bXXXXa |
The second row is worth tracing by hand. Scanning banana left to right: an first appears at index 1 (banana). Replace it and jump forward 2 positions to index 3. an appears again at index 3 (banana). Replace it and jump to index 5. The character at index 5 is a, which does not start another an. Copy it. Result: b + XX + XX + a = bXXXXa.
Working through at least one example by hand before writing code is worth the 60 seconds. It confirms exactly when the index advances by len(s2) versus by 1, which is the detail most candidates get wrong on a first attempt under pressure.
String problems at this level are not about algorithmic complexity. The test is whether you can read a multi-variable problem statement, identify the correct data flow, and translate it into a loop without introducing off-by-one errors. That gap separates candidates who clear the coding section from those who do not.
The Algorithm: Step by Step
The core mechanism is a sliding window. At every position in s1, check whether s2 begins there. If it does, write s3 into the result buffer and advance the index by len(s2). If it does not, copy the current character and advance by 1. Repeat until the end of s1.
Formal steps:
- Step 1: Read
s1,s2, ands3. - Step 2: If
len(s2) == 0, returns1unchanged. This guard prevents an infinite loop. - Step 3: Initialise
result = ""and indexi = 0. - Step 4: While
i < len(s1):- If
s1[i : i + len(s2)] == s2: appends3to result; seti += len(s2). - Else: append
s1[i]to result; seti += 1.
- If
- Step 5: Return result.
Time complexity: O(n x m), where n is len(s1) and m is len(s2). At each of the n positions, up to m character comparisons are made. Space complexity: O(n + r), where r is the net extra length added by all replacements.
The left-to-right greedy approach handles multiple non-overlapping occurrences automatically. Each successful match advances i by len(s2), so no character is revisited in the match branch. No state beyond the current index needs to be tracked.
Code in Python, Java, and C
Python
Python’s str.replace() handles this in one call for production use. For a placement test that asks for a manual implementation, the function below makes the same sliding-window logic explicit:
def replace_substring(s1, s2, s3):
if len(s2) == 0:
return s1
result = ""
i = 0
n2 = len(s2)
while i < len(s1):
if s1[i : i + n2] == s2:
result += s3
i += n2
else:
result += s1[i]
i += 1
return result
s1 = input("Enter string: ")
s2 = input("Substring to replace: ")
s3 = input("Replace with: ")
print(replace_substring(s1, s2, s3))
The one-liner built-in for reference: s1.replace(s2, s3).
Java
import java.util.Scanner;
public class ReplaceSubstring {
public static String replaceManual(String s1, String s2, String s3) {
if (s2.isEmpty()) return s1;
StringBuilder result = new StringBuilder();
int i = 0;
int n2 = s2.length();
while (i < s1.length()) {
if (i + n2 <= s1.length()
&& s1.substring(i, i + n2).equals(s2)) {
result.append(s3);
i += n2;
} else {
result.append(s1.charAt(i));
i++;
}
}
return result.toString();
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s1 = sc.nextLine();
String s2 = sc.nextLine();
String s3 = sc.nextLine();
System.out.println(replaceManual(s1, s2, s3));
sc.close();
}
}
Java’s built-in equivalent is s1.replace(s2, s3). It performs literal matching, not regex, so no special characters in the target need escaping.
C
#include <stdio.h>
#include <string.h>
void replaceSubstring(char *s1, char *s2, char *s3, char *result) {
int i = 0, j = 0;
int n1 = strlen(s1), n2 = strlen(s2), n3 = strlen(s3);
if (n2 == 0) {
strcpy(result, s1);
return;
}
while (i < n1) {
if (strncmp(s1 + i, s2, n2) == 0) {
strcpy(result + j, s3);
j += n3;
i += n2;
} else {
result[j++] = s1[i++];
}
}
result[j] = '\0';
}
int main() {
char s1[200], s2[100], s3[100], result[500];
printf("Enter string: ");
fgets(s1, sizeof(s1), stdin);
s1[strcspn(s1, "\n")] = '\0';
printf("Substring to replace: ");
fgets(s2, sizeof(s2), stdin);
s2[strcspn(s2, "\n")] = '\0';
printf("Replace with: ");
fgets(s3, sizeof(s3), stdin);
s3[strcspn(s3, "\n")] = '\0';
replaceSubstring(s1, s2, s3, result);
printf("Result: %s\n", result);
return 0;
}
The result buffer in C must be large enough for the worst case. When s3 is longer than s2, each replacement grows the output. A safe upper bound is (len(s1) / len(s2)) * len(s3) + len(s1) + 1 bytes.
Built-in vs. Manual: Knowing Both
Every language ships a replace built-in. Wipro interviewers know this. The question pattern that appears in technical rounds is: ask the problem, accept the solution using the built-in, then say “now write it without the replace function.” The second ask is the actual test.
Knowing both matters for two reasons. First, it demonstrates that you understand what the built-in is doing under the hood. Second, it positions you to answer follow-on questions about complexity and edge cases, which the built-in hides from the caller.
There is a third scenario that comes up in Wipro technical interviews: the interviewer asks you to explain what str.replace() does internally. Having implemented the manual version means you can answer directly. You understand that the function scans left-to-right, makes a greedy match, and does not backtrack, because that is exactly what your loop above does.
In production Python code, use str.replace(). In Java, use String.replace(). In a Wipro interview, show both and let the interviewer choose which version to discuss further.
Edge Cases That Trip Candidates
Four situations that differ from the straightforward example and appear in coding assessments:
- Substring not found: the while loop runs to completion without the match branch triggering. The function returns
s1unchanged. No special handling is required beyond what the algorithm already does. - Empty target (
s2 = ""): the manual algorithm above returnss1unchanged via the early-return guard. Python’s built-in insertss3between every character instead, producing a longer string. Know which behaviour your interviewer expects before writing code. - Multiple non-overlapping occurrences: the sliding-window algorithm handles this correctly by design. After each match,
iadvances bylen(s2), so no character is double-processed. - Overlapping-match candidates: the algorithm is greedy-left. With
s1 = "aaa",s2 = "aa",s3 = "b": the match at index 0 is taken,ijumps to 2, one characteraremains and is copied. Result:"ba". Python’s built-in produces the same answer.
In C, always calculate the result buffer size before calling the function. When s3 is longer than s2 and there are several matches, the output can be considerably larger than s1. Allocating only strlen(s1) + 1 bytes is a common buffer-overflow source in C implementations of this problem.
A related consideration in Java: for strings with a large number of replacements, using StringBuilder in the manual implementation (as shown above) is faster than string concatenation with +. Each + in a loop allocates a new object; StringBuilder.append() amortises that cost. For a placement round, either works. For production code, prefer StringBuilder.
Wipro Placement Context
String manipulation is a consistent component of Wipro’s coding assessments. The replace-substring problem tests a specific skill: read the problem, write the traversal loop, handle index arithmetic correctly, and present a clean solution. The typical interview follow-up is predictable: “now implement it without the replace function.” That second ask is what this article prepares you for.
Per Wipro CHRO Saurabh Govil’s Q3 FY26 commentary, Wipro revised its FY26 fresher intake guidance to 7,500-8,000 (down from an earlier guidance of 10,000-12,000). Two hiring tracks are relevant to fresher applicants:
- Standard/Velocity track: ₹3.5 to 4.0 LPA; selected through the NTH test and two interview rounds.
- CoE track: premium above the standard band (exact CTC not publicly disclosed by Wipro); sourced from 50 university Centres of Excellence focused on AI, cybersecurity, and data.
Fewer general-track seats mean each component of the selection process carries more weight. Coding section performance is a primary differentiator at the shortlisting stage.
The Wipro NTH syllabus and pattern guide covers string problem types and their depth in the online test. For more problems in the same format, the Wipro most repeated placement questions collection includes additional string and array exercises. If you are still mapping eligibility and registration windows, the Wipro NQT 2025-2026 exam dates and eligibility guide covers the current process end to end.
String Manipulation in the AI Era
The replace-substring operation sits at the base of most text processing pipelines used in AI systems. Prompt templates swap {user_name} and {context} placeholders using exactly this logic. Output parsers in agentic frameworks strip delimiter tokens with the same left-to-right scan. Preprocessing pipelines for fine-tuning data normalise special characters through targeted replacement passes across large training datasets.
These are direct applications of the algorithm above, running at scale. The code you write for a Wipro placement test and the code inside a production LLM system share the same string-traversal foundation.
If the fundamentals in this article are solid, start with the 2026 AI roadmap for Indian engineering students. It maps the full curriculum from ground-level coding through deployed models.
The entry point for hands-on experimentation is TinkerLLM (₹299 at launch), where you test prompt templates live and observe how string replacement operations affect model output in real time.
Primary sources
Frequently asked questions
What is the time complexity of replace-substring?
O(n x m) for the naive sliding-window approach, where n is the length of the source string and m is the length of the target substring. At each position, up to m characters are compared before the index advances.
Does Python's str.replace() match overlapping occurrences?
No. Python scans left-to-right without backtracking. In 'aaab'.replace('aa', 'b'), the first match at index 0 is replaced and the scan continues from index 2. Only one replacement happens, giving 'bab' not 'bb'.
What is the difference between Java's replace() and replaceAll()?
String.replace(CharSequence, CharSequence) does literal substring matching. String.replaceAll(String, String) treats its first argument as a regular expression. Use replace() for plain text swaps to avoid accidental regex-escape issues.
Is this question still asked in Wipro campus drives in 2025 and 2026?
Yes. String manipulation problems appear in both Wipro NTH online coding tests and in technical interview rounds. The exact framing varies by drive, but the underlying string-traversal skill is tested consistently.
What happens when the target substring is not found in the source string?
The algorithm returns the source string unchanged. The while loop runs to completion without the replacement branch ever being taken, so the output equals the original input exactly.
How do I prevent an infinite loop when the replacement target is an empty string?
Add an early return at the top of the function: if len(s2) == 0, return s1 unchanged. Without that guard, the line i += len(s2) becomes i += 0 and the loop never terminates. Python's built-in str.replace() handles the empty case by inserting s3 between every character of s1.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)