落書きノート

ふと自分が気になった事を書いてます

C++で問題を解く

文字列ポインタ、難しいですね…。紙に書いて考えましたとも。こんな感じです。

#include <iostream>
#include <cstdlib>

using namespace std;

const char* strchr_ptr(const char* s, char c){
    while(*s){
        if(*s == c){
            return s;
        }
        s++;
    }

    return NULL;
}

int main(void){
    char* str = (char*)calloc(16, sizeof(char));
    char c;

    cout << "文字列 : ";
    cin >> str;
    cout << "探す文字 : ";
    cin >> c;

    const char* res = strchr_ptr(str, c);

    if(res == NULL)
        cout << "その文字はありません。" << endl;
    else
        cout << "その文字は" << (res - str) + 1 << "文字目にあります。" << endl;

    return 0;
}
#include <iostream>
#include <cstdlib>

using namespace std;

char* str_rvs(char* s){
    char* save = s;
    char* p = s;
    while(*p)
        p++;
    for(; --p > s; s++){
        char t = *s;
        *s = *p;
        *p = t;
    }
    return save;
}

int main(void){
    char* s = (char*)calloc(16, sizeof(char));
    cout << "文字列 : ";
    cin >> s;
    char* res = str_rvs(s);
    cout << res << endl;
    return 0;
}
#include <iostream>
#include <cstdlib>

using namespace std;

char* str_rvs(char* s){
    char* save = s;
    char* p = s;
    while(*p)
        p++;
    while(--p > s){
        char t = *s;
        *s = *p;
        *p = t;
        s++;
    }
    return save;
}

int main(void){
    char* s = (char*)calloc(16, sizeof(char));
    cout << "文字列 : ";
    cin >> s;
    char* res = str_rvs(s);
    cout << res << endl;
    return 0;
}
#include <iostream>
#include <iomanip>
#include <cstdlib>

using namespace std;

const char* str_match(const char* s1, const char* s2){
    const char* p1 = s1;
    const char* p2 = s2;

    while(*p1 && *p2){
        if(*p1 == *p2){
            p1++;
            p2++;
        }else{
            p1 -= p2 - s2 - 1; // p1 = p1 - (p2 - s2 - 1)と同義。演算と代入とキャストを同時に行っている。
            p2 = s2;
        }
    }

    return *p2 ? NULL : (char*)(p1 - (p2 - s2));
}

int main(void){
    char* str1 = (char*)calloc(16, sizeof(char));
    char* str2 = (char*)calloc(16, sizeof(char));

    cout << "文字列s1 : ";
    cin >> str1;
    cout << "文字列s2 : ";
    cin >> str2;

    const char* res = str_match(str1, str2);

    if(res == NULL)
        cout << "文字列s1の中にs2は含まれません。" << endl;
    else {
        int ofs = res - str1;
        // cout << ofs << endl;
        cout << str1 << endl;
        cout << setw(ofs + 1) << right << "|" << endl;
        cout << setw(ofs) << "" << str2 << endl;
    }

    return 0;
}