简体   繁体   中英

C++ extract each character in string at odd positions and return the even

I need to create a code that will extract the odd positions and return the even postions, so for this code, i need it to return "bd" can anyone point me in the right direction to fix this code so it gives me the output i need? Please note that the main function cannot be changed

string myFunction1(string str) {
    string result = "";                       
    for(int i=1; i<str.length();i+=2) {
        result += str[i]; 
    }
    return result;
}

    int main(){
    assert(myFunction1("abcde").compare("bd") == 0);
}

Use Range-v3

#include <iostream>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/chunk.hpp>
#include <range/v3/view/transform.hpp>
#include <range/v3/view/drop.hpp>
#include <range/v3/view/join.hpp>
#include <string>

using ranges::to;
using namespace ranges::views;

std::string myFunction1(std::string str) {
    return str                 // "abcde", which is [a, b, c, d, e]
         | chunk(2)            // [[a,b], [c,d], [e]]
         | transform(drop(1))  // [[b], [d], []]
         | join                // [b, d]
         | to<std::string>;    // "bd"
}

int main () {
    assert(myFunction1("abcde").compare("bd") == 0);
}
  • the syntax x | f(y) x | f(y) means f(x, y)
  • s , the string, can be seen as a "range" of letters;
  • chunk(2) chunks the input range in chunks of 2 (except that the last chunk has one element if the original string as an odd number of characters)
  • transform(f) applies f to every chunk
  • but f is drop(1) which drops first element/letter of each chunk, leaving only the second elment/letter, thus resulting in a range of singleton ranges (the last can be empty if the original string as an odd number of characters)
  • join joins together the singleon-or-empty ranges into a single range.

This is a solution composed of existing and well tested abstractions, not cluttered with low level details. Understanding and learning to write code like this will pay off.

I have noticed that .length() causes errors sometimes, try to use .size() instead. By the way, your code is good, and it should work. Anyway, try to call the function in the main just to see what's wrong.

Also, you could make the loop go from 1 to str.size() and check if(i%2) then result += str[i] .

I think it's better to put return 0; at the end of main as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM