3

私はこの機能を持っています:

void ToUpper(char * S)
{
    while (*S!=0)
    {
       *S=(*S >= 'a' && *S <= 'z')?(*S-'a'+'A'):*S;
       S++;
    }
} 

* S!= 0の場合、それはどういう意味ですか?代わりにnullにする必要がありますか?

4

5 に答える 5

9

これは、値がゼロの文字である文字列の終わりをチェックすることです。NULLポインタにはまったく接続されていません。

于 2010-03-27T17:19:55.830 に答える
4

もっと慣用的だと思うので書きます*S != '\0'が、それは本当に個人的なスタイルの好みです。ヌル文字(ASCII NUL)をチェックしています。

S != 0ポインタ自体がnullである可能性があり、nullポインタを逆参照したくないため、そのコードの前にチェックすることを検討することもできます。

于 2010-03-27T17:28:55.290 に答える
0

NULLとで異なる方法で定義されCますC++

C

#define NULL 0

C++

#define NULL (void*) 0
于 2010-12-08T19:29:50.237 に答える
-1

NULLはポインタであり、*Sはポインタに格納されている値です。デニス・リッチーのおかげで、数字の0は両方として受け入れ可能です。

于 2010-03-28T11:55:34.293 に答える
-1

私はループよりもアルゴリズムが好きです:

#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;
}
于 2010-03-27T21:03:55.770 に答える