I am new to C++. In order to solve an online puzzle, I needed to extract numbers from strings and keep only the first and last number. For example 4nfhfbk56khfkvh => 456 => 46.
So I made the function given below.
int num_extr(const std::string &thisline){
41
42 std::string stored_numbers = thisline;
43 int i,k,result;
44
45 k = 0;
46
47 for(i=0; i<thisline.size(); i++){
48
49 if(thisline[i] >= '0' && thisline[i] <= '9'){
50 std::cout << "Number: " << thisline[i] << 'n';
51 stored_numbers[k] = thisline[i];
52 ++k;
53 }
54 }
55 std::cout << "Stored_numbers: " << stored_numbers << 'n';
56 std::cout << "Stored_numbers[0]: " << stored_numbers[0] << 'n';
57 std::cout << "Stored_numbers[k-1]: " << stored_numbers[k-1] << 'n';
58 if(k>0){
59 result = ((int)stored_numbers[0] -48) * 10 + ((int)stored_numbers[k-1] -48);
60 }
61 else{
62 result = ((int)stored_numbers[0] -48) * 10 + ((int)stored_numbers[0] -48);
63 }
64 return result;
65 }
As you can see, I assign stored_numbers = thisline, in order to make the string stored_numbers
the same length as thisline (is this faster than using a function to find the length of thisline?). Then, I store the numbers I found on it, starting from [0].
This code works. This is an example of the output:
Initial string: trknlxnv43zxlrqjtwonect
Number: 4
Number: 3
Stored_numbers: 43knlxnv43zxlrqjtwonect
Stored_numbers[0]: 4
Stored_numbers[k-1]: 3
Extracted number: 43
But when I tried to not assign stored_numbers = thisline, so the code would be:
int num_extr(const std::string &thisline){
41
42 std::string stored_numbers;
43 int i,k,result;
44
45 k = 0;
46
47 for(i=0; i<thisline.size(); i++){
48
49 if(thisline[i] >= '0' && thisline[i] <= '9'){
50 std::cout << "Number: " << thisline[i] << 'n';
51 stored_numbers[k] = thisline[i];
52 ++k;
53 }
54 }
55 std::cout << "Stored_numbers: " << stored_numbers << 'n';
56 std::cout << "Stored_numbers[0]: " << stored_numbers[0] << 'n';
57 std::cout << "Stored_numbers[k-1]: " << stored_numbers[k-1] << 'n';
58 if(k>0){
59 result = ((int)stored_numbers[0] -48) * 10 + ((int)stored_numbers[k-1] -48);
60 }
61 else{
62 result = ((int)stored_numbers[0] -48) * 10 + ((int)stored_numbers[0] -48);
63 }
64 return result;
65 }
Then the output is:
Initial string: trknlxnv43zxlrqjtwonect
Number: 4
Number: 3
Stored_numbers:
Stored_numbers[0]: 4
Stored_numbers[k-1]: 3
Extracted number: 43
So when I use stored_numbers as an array of (characters?) without the assignment, it seems like it is no longer one string, but it becomes a set of (pointers?) that cannot be presented as one string on cout…
Is this idea on the right direction? Could someone please explain this behavior in more depth?
1