-6

Is there any way to update the part of a string by passing it in a function?

std::string str = "hello world";

I want to reverse part of the string for example from index 4 to 8.

I have a function that reverses a string from start index to end index. How I can pass the string from index 4 to 8 to that function so that it will be updated automatically in the str string.

Kiril Kirov
  • 37,467
  • 22
  • 115
  • 187
Madu
  • 4,849
  • 9
  • 44
  • 78

3 Answers3

4

Why don't you just use std::reverse?

std::string str = "hello world";
std::reverse ( str.begin() + 4, str.begin() + 8 );
Benj
  • 31,668
  • 17
  • 78
  • 127
2

Write a function that takes begin/end iterators. See, for example std::reverse(). Usage example for std::vector is on the same page.

bobah
  • 18,364
  • 2
  • 37
  • 70
1

You can pass the string by reference:

void foo( std::string & inputString )
{
  //anything you do here will directly affect the string passed.
}

For example:

void foo( std::string & str )
{
    str.append("World!");
}

int main()
{
    std::string a = "Hello, ";
    foo(a);
    std::cout << a;
    return 0;
}

will print out "Hello, World!". Another choice is to pass the begin and end iterators of the string. A lot of std functions work like that.

SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105