どのメモリに格納されていようと std::string の絡む等価演算は同じ内容の文字列であれば true を返してくれる (std::string#compare は 0 を返す)。
サンプルコードと実行結果。
環境はMac OS X Snow Leopard。
$ cat ./stringcompare.cpp
#include <string>
#include <string.h>
#include <stdio.h>
int main(void){
// C
const char* a = "Hello";
char b[6] = "H"; strcat(b, "ello");
printf("a = [%s]\n", a);
printf("b = [%s]\n", b);
if(a == b){
printf("a == b: true\n");
}else{
printf("a == b: false\n");
}
if(strcmp(a, b) == 0){
printf("strcmp(a, b): true\n");
}else{
printf("strcmp(a, b): false\n");
}
// C++
std::string c = std::string(a);
std::string d = std::string(b);
printf("c = [%s]\n", c.c_str());
printf("d = [%s]\n", d.c_str());
if(c == d){
printf("c == d: true\n");
}else{
printf("c == d: false\n");
}
if(c.compare(d) == 0){
printf("c.compare(d): true\n");
}else{
printf("c.compare(d): false\n");
}
if(c.c_str() == d.c_str()){
printf("c.c_str() == d.c_str(): true\n");
}else{
printf("c.c_str() == d.c_str(): false\n");
}
// char* : std::string
if(a == c){
printf("a == c: true\n");
}else{
printf("a == c: false\n");
}
if(a == c.c_str()){
printf("a == c.c_str(): true\n");
}else{
printf("a == c.c_str(): false\n");
}
return 0;
}
$ g++ ./stringcompare.cpp
$ ./a.out
a = [Hello]
b = [Hello]
a == b: false
strcmp(a, b): true
c = [Hello]
d = [Hello]
c == d: true
c.compare(d): true
c.c_str() == d.c_str(): false
a == c: true
a == c.c_str(): false
Ref.
- strcat
- strcmp
- C++文字列(std::string)
tags: c++
Posted by NI-Lab. (@nilab)