Hi, i was dong next of my exercises and i kind of did it but again there were few questions that i was asking myself.
If someone has some free time and likes pointers you are welcome to help :D
Exercise:
Write a function char* findx(const char* s, const char* x )
that finds the first occurrence of the C-style string x in s
1. I couldn't figure out how can i actually return pointer to constant array. As far as i understand its not allowed to give pointers(that are not const) to constant arrays so i removed const from my function's argument list. (Maybe i misunderstood the exercise???)
2. Is there maybe a better way (faster) for getting this job done? (considering i did this exercise the way it was supposed to be done)
#include <iostream>
usingnamespace std;
char* findx(char* s, constchar* x){
//size of x
int size_x = 0;
while (x[size_x]){
size_x++;
}
if (!size_x) returnnullptr;
//size of s
int size_s = 0;
while (s[size_s]){
size_s++;
}
//looking for address of where x starts in s
for (int i = 0; i < size_s; i++){ //scanning through s
if (s[i] == x[0]){
//if 1st char in "s" is the same as in "x" look for the rest
int chars_found = 0;
for (int j = 0; j < size_x; j++){
if (s[i + j] != x[j]){ break; }
else { chars_found++; }
}
//if found all the chars return starting address of this name in s
if (chars_found == size_x) return &s[i];
}
}
//if nothing was found return nullptr
returnnullptr;
}
int main(){
char c_str[] = "Hello world!";
char x[] = "world";
char* p = findx(c_str, x);
if (p){
cout << p[0] << p[1] << p[2] << p[3] << p[4] << endl;
}
else cout << "its nullptr" << endl;
system("pause");
}
I don't think that's a logic error. The p pointer is supposed to give the address in the original c-string that he finds the first occurrence of the search c-string. Since the original string is basically "Hello world!\0", then if you print it out starting from the first occurrence of world, you get "world!\0". (I included the null char because I think that makes it clearer.)