私はこの機能を持っています:
void ToUpper(char * S)
{
while (*S!=0)
{
*S=(*S >= 'a' && *S <= 'z')?(*S-'a'+'A'):*S;
S++;
}
}
* S!= 0の場合、それはどういう意味ですか?代わりにnullにする必要がありますか?
これは、値がゼロの文字である文字列の終わりをチェックすることです。NULLポインタにはまったく接続されていません。
もっと慣用的だと思うので書きます*S != '\0'
が、それは本当に個人的なスタイルの好みです。ヌル文字(ASCII NUL)をチェックしています。
S != 0
ポインタ自体がnullである可能性があり、nullポインタを逆参照したくないため、そのコードの前にチェックすることを検討することもできます。
NULL
とで異なる方法で定義されC
ますC++
のC
#define NULL 0
のC++
#define NULL (void*) 0
NULLはポインタであり、*Sはポインタに格納されている値です。デニス・リッチーのおかげで、数字の0は両方として受け入れ可能です。
私はループよりもアルゴリズムが好きです:
#include <algorithm>
#include <cstring>
#include <cctype>
void ToUpper(char* p)
{
std::transform(p, p + strlen(p), p, toupper);
}
このソリューションは、aからzが連続していない文字エンコードでも機能します。
楽しみのために、アルゴリズムを使用して1回の反復のみを行う実験を次に示します。
#include <algorithm>
#include <cassert>
#include <cstring>
#include <cctype>
#include <iostream>
#include <iterator>
struct cstring_iterator : std::iterator<std::random_access_iterator_tag, char>
{
char* p;
cstring_iterator(char* p = 0) : p(p) {}
char& operator*()
{
return *p;
}
cstring_iterator& operator++()
{
++p;
return *this;
}
bool operator!=(cstring_iterator that) const
{
assert(p);
assert(!that.p);
return *p != '\0';
}
};
void ToUpper(char* p)
{
std::transform(cstring_iterator(p), cstring_iterator(),
cstring_iterator(p), toupper);
}
int main()
{
char test[] = "aloha";
ToUpper(test);
std::cout << test << std::endl;
}