转载自:https://blog.csdn.net/wangshubo1989/article/details/50155093
如果声明了一std::string类型,怎么初始化呢?
std::string test_string;
std::string test_string_empty = "";
std::string test_string_null = NULL;//运行错误,而非编译错误
- 1
- 2
- 3
简单测试:
#include<iostream>
int main()
{
std::string test_string;
std::string test_string_empty = "";
// std::string test_string_null = NULL;
if (test_string == "")
{
std::cout << "test_string is empty!" << std::endl;
}
if (test_string_empty == "")
{
std::cout << "test_string_empty is empty!" << std::endl;
}
return 0;
}
/*---------------------------------
输出:
test_string is empty!
test_string_empty is empty!
-----------------------------------*/
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
由此可见,声明一个std::string对象,默认变为空。
更重要的是 std::string不能与null进行比较!!
那么判断一个std::string 为空 是使用empty还是“”呢?
#include<iostream>
int main()
{
std::string test_string;
std::string test_string_empty = "";
// std::string test_string_null = NULL;
if (test_string == "")
{
std::cout << "test_string is empty!" << std::endl;
}
if (test_string_empty.empty())
{
std::cout << "test_string_empty is empty!" << std::endl;
}
if (test_string_empty.length() == 0)
{
std::cout << "test_string_empty is empty!" << std::endl;
}
return 0;
}
//输出:
//test_string is empty!
//test_string_empty is empty!
//test_string_empty is empty!
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
三种方法都可以,但是谁更优越呢?
之前搞过一段C Sharp, 犹记得比较长度最快,不知道C++中是不是也是通过长度来判断字符串是否为空的方法最为效率呢。
太晚了,明天继续,欢迎指导:
#include<iostream>
#include <ctime>
#include<Windows.h>
int main()
{
std::string test_string;
std::string test_string_empty = "";
unsigned int ticks1 = 0;
unsigned int ticks2 = 0;
unsigned int ticks3 = 0;
unsigned int ticks4 = 0;
unsigned int ticks5 = 0;
unsigned int ticks6 = 0;
ticks1 = GetTickCount();
if (test_string_empty == "")
{
for (int i = 0; i < 100000; i++)
{
}
ticks2 = GetTickCount();
}
ticks3 = GetTickCount();
if (test_string_empty.empty())
{
for (int i = 0; i < 100000; i++)
{
}
ticks4 = GetTickCount();
}
ticks5 = GetTickCount();
if (test_string_empty.length() == 0)
{
for (int i = 0; i < 100000; i++)
{
}
ticks6 = GetTickCount();
}
std::cout << ticks2 - ticks1 << std::endl;
std::cout << ticks4 - ticks3 << std::endl;
std::cout << ticks6 - ticks5 << std::endl;
return 0;
}
//test_string is empty!
//test_string_empty is empty!