牛骨文教育服务平台(让学习变的简单)

没有躲过的坑--std::string初始化、最快速判断字符串为空

之前说过,记得给变量初始化。

今天突然想到了一个问题,如果声明了一std::string类型,怎么初始化呢?

std::string test_string;
std::string test_string_empty = "";
std::string test_string_null = NULL;//运行错误,而非编译错误

简单测试:

#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!
-----------------------------------*/

由此可见,声明一个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!

三种方法都可以,但是谁更优越呢?

之前搞过一段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!