Ashok is developing a text processing utility that allows users to insert a substring into an original string at a specified position. The program takes input for the original string, the substring to insert, and the position at which to insert the substring.
Write a program to help Ashok using the methods of the StringBuilder class.
Input format: - The first line of input contains a string representing the original string. - The second line of input contains a string representing the substring to insert. - The third line of input contains an integer representing the index position to insert the substring (index starts from 0).
Output format: - The output prints a string representing the modified string after inserting the substring.
Solution:
class StringManipulation {
public static String insertSubstring(String originalString, String substringToInsert, int insertionPosition) {
StringBuilder sb = new StringBuilder(originalString);
sb.insert(insertionPosition, substringToInsert);
return sb.toString();
}
}
Sophia is working on a program to combine two strings into a new one by concatenating their characters while ensuring that no character is repeated in the final result.
Write a program to merge two strings into one by retaining only unique characters in the order they first appear using the StringBuilder class.
Input format:
- The first line contains a string representing the firstString
, which consists of alphanumeric characters, spaces, and symbols.
- The second line contains a string representing the secondString
, with the same format as firstString
.
Output format:
- The output prints a single string containing all unique characters from firstString
and secondString
in the order of their first appearance.
Solution: ```java class StringManipulation { public static String concatenateUnique(String firstString, String secondString) { StringBuilder result = new StringBuilder();
// Flag to track unique characters
boolean[] seen = new boolean[256]; // Assumes ASCII characters
// Process first string
for (char c : firstString.toCharArray()) {
if (!seen[c]) {
result.append(c);
seen[c] = true;
}
}
// Process second string
for (char c : secondString.toCharArray()) {
if (!seen[c]) {
result.append(c);
seen[c] = true;
}
}
return result.toString();
}
}