it9kelvin
it9kelvin

Reputation: 11

slicing a string with the corresponding position

using namespace std;

int main()
{
    string s = "12125.34e9";
    int dot_pos = s.find('.');
    int e_pos = s.find('e');
    cout<<s.substr(dot_pos+1, e_pos-1);
    return 0;
}

I try to get the string "34e".
I have tried s.substr(dot_pos+1, e_pos-1) and s.substr(dot_pos+1, e_pos)
It always return "34e9" for no reason.

Upvotes: 1

Views: 151

Answers (4)

Marek R
Marek R

Reputation: 37607

I really really recommend to get familiar with writing tests, this will allow you to spot and fix problem with code fast.

Here is an example:

#include "catch2/catch_all.hpp"

std::string extractFracExp(const std::string& s)
{
    auto dot = s.find('.');
    auto e = s.find('e', dot + 1);
    if (dot == std::string::npos || e == std::string::npos)
        return {};

    return s.substr(dot + 1, e - dot - 1);
}

TEST_CASE("extractFracExp") {
    auto [s, expected] = GENERATE(table<std::string, std::string>({
        { "", "" },
        { "1", ""},
        { "1e12", ""},
        { "1.2123", ""}, // ??? is this your requriement
        { "1.32e21", "32"},
        { "12125.34e9", "34"},
    }));

    INFO("s = " << s);
    REQUIRE(extractFracExp(s) == expected);
}

Live example

Upvotes: 0

Shawn
Shawn

Reputation: 52344

You can also use an iterator range:

std::cout << std::string{s.begin() + dot_pos + 1, s.begin() + e_pos + 1} << '\n':

Upvotes: 0

dtell
dtell

Reputation: 2568

substr returns a sub-string starting from a given position of a given length, hence you need to do something like this

std::string s = "12125.34e9";

// get position of .
int dot_pos = s.find('.');

// get position of e
int e_pos = s.find('e');

// how many chars between . and e?
int diff = e_pos - dot_pos;

// get sub-string of length diff starting from dot_pos
std::cout << s.substr(dot_pos + 1, diff) << "\n";

Outputs

34e

Upvotes: 1

Holt
Holt

Reputation: 37606

You are using .substr() incorrectly, see the documentation. The second parameter is the number of elements you want after the start, so you wwant something like

s.substr(dot_pos + 1, e_pos - dot_pos);

Upvotes: 3

Related Questions