You can use the standard alfgorithm std::find
. For example
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
int main()
{
std::vector<std::string> v =
{
"Egg", "Milk", "Sugar", "Chocolate", "Flour"
};
const char *src = "Sugar";
const char *dsn = "Honey";
auto it = std::find( v.begin(), v.end(), src );
if ( it != v.end() ) *it = dsn;
for ( const auto &s : v ) std::cout << s << ' ';
std::cout << std::endl;
return 0;
}
The program output is
Egg Milk Honey Chocolate Flour
If you want to replace all occurences of "Sugar" then you can use the standard algorithm std::replace
.
For example
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
int main()
{
std::vector<std::string> v =
{
"Egg", "Milk", "Sugar", "Chocolate", "Flour", "Sugar"
};
const char *src = "Sugar";
const char *dsn = "Honey";
std::replace( v.begin(), v.end(), src, dsn );
for ( const auto &s : v ) std::cout << s << ' ';
std::cout << std::endl;
return 0;
}
The program output is
Egg Milk Honey Chocolate Flour Honey
If you mean the substitution only in the function print
within the loop then the function can look the following way
#include <iostream>
#include <vector>
#include <string>
void print( const std::vector<std::string> &v,
const std::string &src = "Sugar",
const std::string &dsn = "Honey" )
{
for ( std::vector<std::string>::size_type i = 0; i < v.size(); i++ )
{
std::cout << "[" << i << "] " << ( v[i] == src ? dsn : v[i] ) << "\n";
}
}
int main()
{
std::vector<std::string> v =
{
"Egg", "Milk", "Sugar", "Chocolate", "Flour"
};
print( v );
return 0;
}
Its output is
[0] Egg
[1] Milk
[2] Honey
[3] Chocolate
[4] Flour