微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

字符串生成器方法

如何解决字符串生成器方法

我尝试使用以下方法编写字符串构建器模式:

append(string s) // Input a string and add it to the list
reverse() // Input a string and reverse him
toString() // Return the string of all the chars in the list
apply // Given a function it will apply it to all characters

所以前 3 种方法都有效,这就是我的 code

class MyStringBuilder {
    int size;
    char* myString;
public:
    // CTOR
    MyStringBuilder():size(0) {
        myString = new char[size + 1];
    } 
    // DTOR
    ~MyStringBuilder() { 
        cout<<"DTOR"<<endl;
        if (myString != nullptr) {
            delete[] myString;
        }
    }
    int sizeChars(const char* s) {
        int count = 0;
        while(*s != '\0') {
            s++;
            count++;
        }
        return count;
    }
    MyStringBuilder& append(const char* s) {
        int count = sizeChars(s);
        char* helper;
        helper = new char[size + 1];
        strcpy(helper,myString);
        myString = new char[size + count + 1];
        strcpy(myString,helper);
        strcpy(myString + size,s);
        size += count;
        delete [] helper;
        return *this;
    }
    MyStringBuilder& reverse() {
        size = strlen(myString);
        for(int i = 0; i < strlen(myString) / 2; i++) {
            char temp = myString[i];
            myString[i] = myString[strlen(myString) - i - 1];
            myString[strlen(myString) - i - 1] = temp;
        }
        return *this;
    }
   
    string toString() {
        string s(myString);
        return s;
    }
};

所以除了 apply 方法之外,一切都在工作,我看到在 java 的主函数中它是这样写的:

String s = sb.append("abc").append("def").reverse().apply(c->(char)(c-('a'-'A'))).toString(); // s=FEDCBA 

我们如何在 c++ 中编写 apply 方法?以及如何将java的线函数转换为cpp

解决方法

MyStringBuilder& append(char (*op)(char))  {
  for (char* c = myString; c < myString + size; c++)
   *c = op(*c);
  return *this;
}

如果你想接受有状态的 lamdas 然后声明函数

MyStringBuilder& append(std::function<char(char)> op)

MyStringBuilder& append(auto op)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。