Replace values within string

2

How do I replace values within a string ?

The string will look like this:

gabriel = 1.73,derp = 1.80,

Take into account that this structure is: nome = altura, nome = altura, .

In case, I want to replace the height of gabriel by 1.75, but I do not know how to tinker with patterns in c ++.

I would like to search for something like 'gabriel = (% d +)' and replace with 'gabriel = 1.75'.

Name size can be larger or smaller.

Height can have more numbers and other values.

On Lua it would look like this:

local str = "gabriel = 1.73, derp = 1.80,"
local size = string.match(str, 'gabriel = (.-),')
print(str)
str = string.gsub(str, 'gabriel = '..size..',', 'gabriel = 1.75,')
print(str)

See working on ideone.

    
asked by anonymous 12.02.2015 / 08:45

2 answers

2

After editing I saw that the problem was another. Moon and C ++ have a pattern - with unintentional pun parody - of different regular expression patterns. It is necessary to make a "translation". And obviously the functions are slightly different. It would look like this:

#include <regex>
#include <string>
#include <iostream>
using namespace std;

int main() {
    string texto = "gabriel = 1.73,derp = 1.80,";
    regex padrao("gabriel = (.*?),");
    cout << regex_replace(texto, padrao, "gabriel = 1.75,");
    return 0;
}

See running on ideone .

I do not like to use RegEx and would do otherwise, because this pattern is very simple but it's there as you wish.

I think it's this function you want:

#include <iostream>
using namespace std;

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;
}

int main() {
    string texto = "gabriel = 1.73,derp = 1.80,";
    replace(texto, "1.73", "1.75");
    cout << texto;
    return 0;
}

See working on ideone .

    
12.02.2015 / 12:49
3

In this code, it is possible for the user to insert the string to be searched in the standard phrase (contents of the string sWord variable) and the user can also enter the value of the height to be replaced.

Here is the code for this application:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string sNum1;
    string sWord = "Este texto contem gabriel = 1.73,derp = 1.80, essa foi uma busca.";
    string nomeProcurado;
    int iPosInicial, iTam;

    cout << "\nTexto Inicial: " << sWord << "\n";

    cout << "\nString a ser procurada: ";
    cin >> nomeProcurado;
    iPosInicial = sWord.find(nomeProcurado);

    cout << "Digite o novo valor: ";
    cin >> sNum1;

    iTam = nomeProcurado.length();

    sWord.replace(iPosInicial+iTam+3,4, sNum1);

    cout << "\nTexto Alterado: " << sWord << "\n";

    return 0;
}

See working at ideone: link

    
12.02.2015 / 17:24