あなたが持っているとしましょう:
const char * something = "m";
toupper (または該当する場合は他の何か) を使用して、この大文字をどのように作成しますか?
char *
a の代わりに aを使用したいstring
(文字列を使用できますが、使用する必要がありますstr.c_str()
)。
では、どうすればchar * something = "m";
含むことができます"M"
か?
C弦の選択が邪魔だと思います..でもとにかく。
文字列リテラル ( ) は変更できませんchar *something
。配列を試してください:
char something[] = "m";
something[0] = toupper(something[0]);
文字列全体を変更するには:
char something[] = "hello";
char *p = something;
while (*p) {
*p = toupper(*p);
p++;
}
非常に有名な C の本のセクションで説明されているThe C Programming Language
ようKernighan & Ritchie
に5.5 Character Pointers and Functions
、
char amessage[] = "now is the time"; /* an array */
char *pmessage = "now is the time"; /* a pointer */
`amessage` is an array, just big enough to hold the
sequence of characters and `'\0'` that initializes it.
Individual characters within the array may be changed
but `amessage` will always refer to the same storage.
On the other hand, `pmessage` is a pointer, initialized
to point to a string constant; the pointer may subsequently
be modified to point elsewhere, but the result is undefined
if you try to modify the string contents.
OTOH, in C, 大文字に変換するには、次のプログラムを参考にしてください。
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int i=0;
char str[]="Test String.\n";
char c;
while (str[i]) {
c=str[i];
putchar(toupper(c));
i++;
}
return 0;
}
C++ の場合
#include <iostream>
#include <string>
#include <locale>
using namespace std;
int main ()
{
locale loc;
string str="Test String.\n";
for (size_t i=0; i<str.length(); ++i)
cout << toupper(str[i],loc);
return 0;
}
EDIT:Cバージョンのポインターバージョン(@Johnの要求による)の追加
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int i=0;
char str[]="Test String.\n";
char *ptr = str;
while (*ptr) {
putchar(toupper(*ptr));
ptr++;
}
return 0;
}
それが役に立てば幸い!
std::string
生の配列について知っているのと同じアルゴリズムのアプローチを使用できます。
char s[] = "hello world";
std::transform(s, s + std::strlen(s), s, static_cast<int(*)(int)>(std::toupper));
const char * s = "hello world;"
明らかな理由により、不変の文字列リテラル( など)に対してこれを行うことはできないため、そのための追加の割り当て/コピーを回避することはできません。
更新: Ildjarn がコメントで述べているように、文字列リテラルは常に読み取り専用であることに注意することが重要char * s = "hello world";
です。これを試みた場合、まともなC++コンパイラはあなたを平手打ちするはずですが、それは有効なC++ですが、の要素を実際に変更s
しようとすると、未定義の動作になります。
C-string を std::string に変換してから、boost::to_upper を使用して文字列をその場で変更するか、boost::to_upper_copy を使用して文字列の大文字のコピーを作成できます。コード例は次のとおりです。
#include <iostream>
#include <boost/algorithm/string/case_conv.hpp>
int main ()
{
char const * s = "Test String.\n";
std::string str(s);
std::cout << boost::to_upper_copy(str).c_str() << std::endl;
return 0;
}
お役に立てれば。
あなたがすることができます:
#include <algorithm>
#include <iterator>
#include <ctype.h>
char test[] = "m";
std::transform(std::begin(test), std::end(test), std::begin(test), ::topper);
これにより、::toupper
関数が文字列の文字に適用されます。これは、::toupper
C に由来するグローバル名前空間の関数です。std::toupper
複数のオーバーロードがあり、::toupper
よりエレガントに見えますstatic_cast<int (*)(int)>(&std::toupper)
。