Replace Part of a String With Another String

Replace part of a string with another string

There's a function to find a substring within a string (find), and a function to replace a particular range in a string with another string (replace), so you can combine those to get the effect you want:

bool replace(std::string& str, const std::string& from, const std::string& to) {
size_t start_pos = str.find(from);
if(start_pos == std::string::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}

std::string string("hello $name");
replace(string, "$name", "Somename");

In response to a comment, I think replaceAll would probably look something like this:

void replaceAll(std::string& str, const std::string& from, const std::string& to) {
if(from.empty())
return;
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}

How to replace a part of a string with another substring

Replacing a substring with another is easy if both substrings have the same length:

  • locate the position of the substring with strstr
  • if it is present, use memcpy to overwrite it with the new substring.
  • assigning the pointer with *strstr(m, "on") = "in"; is incorrect and should generate a compiler warning. You would avoid such mistakes with gcc -Wall -Werror.
  • note however that you cannot modify a string literal, you need to define an initialized array of char so you can modify it.

Here is a corrected version:

#include <stdio.h>
#include <string.h>

int main(void) {
char m[] = "cat on couch";
char *p = strstr(m, "on");
if (p != NULL) {
memcpy(p, "in", 2);
}
printf("%s\n", m);
return 0;
}

If the replacement is shorter, the code is a little more complicated:

#include <stdio.h>
#include <string.h>

int main(void) {
char m[] = "cat is out roaming";
char *p = strstr(m, "out");
if (p != NULL) {
memcpy(p, "in", 2);
memmove(p + 2, p + 3, strlen(p + 3) + 1);
}
printf("%s\n", m);
return 0;
}

In the generic case, it is even more complicated and the array must be large enough to accommodate for the length difference:

#include <stdio.h>
#include <string.h>

int main(void) {
char m[30] = "cat is inside the barn";
char *p = strstr(m, "inside");
if (p != NULL) {
memmove(p + 7, p + 6, strlen(p + 6) + 1);
memcpy(p, "outside", 7);
}
printf("%s\n", m);
return 0;
}

Here is a generic function that handles all cases:

#include <stdio.h>
#include <string.h>

char *strreplace(char *s, const char *s1, const char *s2) {
char *p = strstr(s, s1);
if (p != NULL) {
size_t len1 = strlen(s1);
size_t len2 = strlen(s2);
if (len1 != len2)
memmove(p + len2, p + len1, strlen(p + len1) + 1);
memcpy(p, s2, len2);
}
return s;
}

int main(void) {
char m[30] = "cat is inside the barn";

printf("%s\n", m);
printf("%s\n", strreplace(m, "inside", "in"));
printf("%s\n", strreplace(m, "in", "on"));
printf("%s\n", strreplace(m, "on", "outside"));
return 0;
}

Replace part of a string in Python?

>>> stuff = "Big and small"
>>> stuff.replace(" and ","/")
'Big/small'

Replace part of string if another string exists

Can be done with a regex pattern using positive lookbehind with the wanted variable inserted in it:

let str1 = "RHID='1' AND CD_FF='Cartão Crédito'";
const str2 = "'Marca/Modelo'"; // no need to hardcode CD_FF here

const variable = "CD_FF"; // can be taken from anywhere

const pattern = new RegExp(`(?<=${variable}=).*`);
str1 = str1.replace(pattern, str2);

console.log(str1);

Output:

RHID='1' AND CD_FF='Marca/Modelo'

Note that str3 is not needed for anything and also that this code correctly does no replacements if the CD_FF (or whatever is in variable) is not found from the str1.

How to replace part of a String in Java?

Use regex like this :

public static void main(String[] args) {
String s = "Hello my Dg6Us9k. I am alive";
String newString=s.replaceFirst("\\smy\\s\\w{7}", "");
System.out.println(newString);
}

O/P :
Hello. I am alive

replace part of the string in C#

Well, well well

Take your universal method:

        public string Replacement(string input, string replacement)
{
string[] words = input.Split(' ');
string result = string.Empty;

for (int i = 0; i < words.Length; i++)
{
if(words[i].Contains('/'))
{
int barIndex = Reverse(words[i]).LastIndexOf('/') + 1;
int removeLenght = words[i].Substring(barIndex).Length;
words[i] = Reverse(words[i]);
words[i] = words[i].Remove(barIndex, removeLenght);
words[i] = words[i].Insert(barIndex, Reverse(replacement));
string ToReverse = words[i];
words[i] = Reverse(ToReverse);

break;
}
}

for(int i = 0; i < words.Length; i++)
{
result += words[i] + " ";
}

result = result.Remove(result.Length - 1);

return result;
}

public string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}

In reponse to >> I need a universal method to replace any stuff between the slash and the space closest to it



Related Topics



Leave a reply



Submit