肉とビールとパンケーキ by @sotarok

少し大人になった「肉とご飯と甘いもの」

strtoupperとucwordsをC言語で実装してみた

久々のお勉強シリーズ(笑)

ここらへんで見てみた、PHPC言語による実装ですが、見てみて、ああなるほどね、と理解したつもりで、じゃあC言語でこれ動くようにしてみてよ、といわれるとあまり自信がないなーと思ったので、ちょうど良いのでC言語で書いてみた感じです。

まあ文字列の扱いあんま得意じゃなかったので。

#include <stdio.h>
#include <string.h>

#define MAX_LENGTH 255

int strtoupper (char *);
int ucwords (char *);

//{{{
int main ()
{
        char input[MAX_LENGTH], *string;

        // 文字列を入力
        fgets(input, MAX_LENGTH, stdin);
        printf("original   : %s", input);

        // 入力された文字分だけメモリ確保
        string = (char *)malloc(sizeof(input));
        
        // オリジナルをコピー   
        strcpy(string, input);

        // すべて大文字に変えて出力
        printf("strtoupper : %s", strtoupper(string));

        strcpy(string, input);
        // 単語の最初だけ大文字に変えて出力
        printf("ucwords    : %s", ucwords(string));

        return 0;
}
//}}}

//{{{
int strtoupper (char *str)
{
        char *tmp = str;

        // 順に見てすべて大文字に変更
        while (*tmp != '\0') {
                *tmp = toupper(*tmp++);
        }

        // string の先頭アドレスを返す 
        return (int)str;
}
//}}}

//{{{
int ucwords (char *str)
{
        char *tmp = str;

        // 最初の文字は大文字にする
        *tmp = toupper(*tmp++);
        while (*tmp != '\0') {
                // 順に見て、空白があれば次の文字を大文字にする
                if (isspace((int)*tmp++)) 
                        *tmp = toupper(*tmp);
        }
        return (int)str;
}
//}}}

で、実行結果は、

this is my first hello world!!
original   : this is my first hello world!!
strtoupper : THIS IS MY FIRST HELLO WORLD!!
ucwords    : This Is My First Hello World!!
Digg is a place for people to discover and share content from anywhere on the web. From the biggest online destinations to the most obscure blog, Digg surfaces the best stuff as voted on by our users.
original   : Digg is a place for people to discover and share content from anywhere on the web. From the biggest online destinations to the most obscure blog, Digg surfaces the best stuff as voted on by our users.
strtoupper : DIGG IS A PLACE FOR PEOPLE TO DISCOVER AND SHARE CONTENT FROM ANYWHERE ON THE WEB. FROM THE BIGGEST ONLINE DESTINATIONS TO THE MOST OBSCURE BLOG, DIGG SURFACES THE BEST STUFF AS VOTED ON BY OUR USERS.
ucwords    : Digg Is A Place For People To Discover And Share Content From Anywhere On The Web. From The Biggest Online Destinations To The Most Obscure Blog, Digg Surfaces The Best Stuff As Voted On By Our Users.

こんなかんじ。

意外とうまくいった。(笑)

ていうかやっぱり苦労した。ポインタ。だいぶC言語触ってなかったから、なんか「こうしてこうだよね」みたいな話ができても、じゃあそれを自分で書いてみてよ、といわれるとやっぱり自信がないんだな。まあちょくちょく思い出したときにこうやって復習しながら勉強しようと。。
やっぱり書けば書くほど理解が深まる。