Changing/Transforming

Hey guys, i wonder if you know how to change a letter from a word.

For example, i want the letter "a" to always change to b or whatever i want to be its place.So when i write "alarm" it will give me "blbrm".

Edit: well never mind i found a rather nice solution using replace :)
Last edited on
New problem >.<

how do i replace "m" with "n" and "m" with "n"

Example: i write NM and i want MN

instead i get MM...
replace n with (e.g.) - and m with (e.g.) +. Then replace - with m and + with n.
clever :D thanks a lot!
A more flexible solution might involve std::transform.
The problem with coder777's method is that it uses "special characters" that thus cannot occur in the word.

There is a command line program, tr http://en.wikipedia.org/wiki/Tr_%28Unix%29
# echo "number" | tr 'men' 'nom'
munbar

The replacements for a position are simultaneous. Multiple calls to replace are not simultaneous.

The possible implementation for replace contains a loop:
1
2
3
4
5
6
while (first!=last) {
  if (*first == old_value) {
    *first = new_value;
  }
  ++first;
}

The loop looks at one character at a time.
The std::transform is a loop that looks at one element (character) at a time.

What should we do for a character? In replace there is one test. We could expand on that:
1
2
3
4
5
6
7
8
9
while (first!=last) {
  if (*first == 'm') {
    *first = 'n';
  }
  else if (*first == 'n') {
    *first = 'm';
  }
  ++first;
}

Now at most one replacement does occur for every character in the word. However, that is now hardcoded for 'nm' and it is hard to expand. The tr seems way more flexible.

The tr is a GNU tool. Open source. We can read what it does.

But why read when we can think?

We have a character. Can we find it from our match-list? If yes, then replace the character with corresponding element of substitute-list.

For example, we are looking at 'e'. We find it from "men" at position 1. Position 1 in "nom" is 'o'. Replace 'e' with 'o'.
We look at 'r'. It is not in "men". It remains unchanged.

Rather than position numbers and two separate lists, one could use pairs of characters: http://www.cplusplus.com/reference/unordered_map/unordered_map/find/
Topic archived. No new replies allowed.