실패한 코드

#include <string>
#include <algorithm>
using namespace std;

string step7(string id){
    if(id.length()<=2){
        id.append(3-id.length(), id[id.length()-1]);
    }
    return id;
}

string step6(string id){
    if(id.length()>15){
        id.erase(15, id.length()-15);
    }
    return step7(id);
}

string step5(string id){
    if(id.length()==0){
        id = "a";
    }
    return step6(id);
}

string step4(string id){
    if((id.at(0)=='.')==1){
        id.erase(0,1);
    }
    if((id.at(id.length()-1)=='.')>0){
        id.erase(id.length()-1,1);
    }
    return step5(id);
}

string step3(string id){
    int pos = 0;
    string points = "..";

    while((pos = id.find(points, pos)) != std::string::npos){
        id.replace(pos, points.length(), ".");
    }
    if(id.length()==0){
        step5(id);
    }
    return step4(id);
}

string step2(string id){
    int i=0;
    for(int i=0;i< id.length(); i++){
        if(97>(int)id.at(i)||122<(int)id.at(i)){
            if(id.at(i)=='-'||id.at(i)=='_'||id.at(i)=='.'){
                continue;
            }
            id.erase(i,1);
            i--;
        }
    }
    if(id.length()==0){
        step5(id);
    }
    return step3(id);
}

string step1(string id){
    if(id.length()==0){
        step5(id);
    }
    for(int i=0; i< id.length(); i++){
        id.at(i) = tolower(id.at(i));
    }
    return step2(id);
}

string solution(string new_id) {
    string answer = step1(new_id);
    return answer;
}
int main() {
    string answer = solution("=.=");

    printf("%s", &answer);

    return 0;
}

 

 

 

성공한 코드

#include <string>
#include <vector>

using namespace std;

string solution(string new_id) {
    string answer = "";


    //step 1
    for(char& c:new_id)
        c = tolower(c);

    //step 2
    for(char c:new_id){
        if(c!='-'&& c!='_' && c!='.' && !('a'<=c&&c<='z') && !('0'<=c&&c<='9'))
            continue;
        answer.push_back(c);
    }

    //step 3
    int pos = 0;
    string points = "..";

    while((pos = answer.find(points, pos)) != std::string::npos){
        answer.replace(pos, points.length(), ".");
    }

    //step4
    if(!answer.empty()&&answer.at(0)=='.'){
        answer.erase(0,1);
    }
    if(!answer.empty()&&answer.at(answer.size()-1)=='.'){
        answer.erase(answer.length()-1,1);
    }

    //step5
    if(answer.empty()) answer="a";

    //step6
    if(answer.length()>15){
        answer.erase(15, answer.length()-15);
    }
    if(answer.at(answer.size()-1)=='.'){
        answer.erase(answer.length()-1,1);
    }


    //step7
    if(answer.length()<=2){
        answer.append(3-answer.length(), answer[answer.length()-1]);
    }
    return answer;
}​

 

for문에서 char 다루는 법을 익히자!!

그리고 new_id에서 지워가는 것 말고, answer에 쌓아가는 방법도 존재한다는 깨달음 🐣