简体   繁体   中英

C++ Call string into function?

Not sure how to exactly explain this, sorry. I'm creating a function to find the first instance of a char in an array built by a given string. I have the function to create an array from the string and loop through the array, but not sure how to put it the array into the find function.

the tester is built like

stringName("Test test test");

stringName.find("e",0);  //where 0 is the starting position, so it would return 1. 
int SuperString::find(char c, int start) {
// put array grabber thing here
size = *(&data + 1) - data;
    for(int i = start; i < size ; i++){
        if(data[i] == c){
            return i;
            }
    }
   return -1;
   
    } 

This is what I have to make the string into an array.

SuperString::SuperString(std::string str) {
    size = str.size();
    data = new char[size];
    for (int i = 0; i < size; i++) {
        data[i] = str.at(i);
    }

}

This is probably something easy I'm missing, but any help is appreciated.

You are passing a string literal, specifically a const char[2] , where a single char is expected. Use 'e' instead of "e" :

stringName.find('e', 0);

More importantly, size = *(&data + 1) - data; will only work when data is a (reference to a) fixed array (see How does *(&arr + 1) - arr give the length in elements of array arr? ). It will not work when data is a pointer to an array, as it is in your case since you are allocating the array with new char[] . You will have to keep track of the array's size separately, which you appear to be doing, except that you are not actually using the size you obtained in the SuperString constructor. Just get rid of the line in find() that is trying to re-calculate size , use the value you already have:

int SuperString::find(char c, int start) {
    // size = *(&data + 1) - data; // <-- GET RID OF THIS
    for(int i = start; i < size; ++i){
        if (data[i] == c){
            return i;
        }
    }
    return -1;
} 

That being said, Your SuperString class can be greatly simplified if you just make its data member be a std::string instead of char* , eg:

#include <string>

class SuperString {
private:
    std::string data;
    ...
public:
    SuperString(const std::string &str);
    int find(char c, int start = 0);
    ...
};

SuperString::SuperString(const std::string &str) : data(str) {
}

int SuperString::find(char c, int start) {
    return (int) data.find(c, start);
} 

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