(十五)QT专题-C++字符串

2023-02-21  本文已影响0人  GoodTekken

C++中,字符串(character string)最为基本的表达方式就是使用一个以空字节(‘\0’)为结束符的字符数组。下面的4个函数给出了字符串的这些方式:

void hello1()
{
 const char str[] = {'H', 'e', 'l', 'l', 'o', '  ', 'w', 'o', 'r', 'l', 'd', '\0'};
 std::cout<< str <<std::endl;
}
void hello2()
{
 const char str[] = "Hello world!";
 std::cout<< str <<std::endl;
}
void hello3()
{
 std::cout<< "Hello world!"<<std::endl;
}
void hello4()
{
 const char* str = "Hello world!";
 std::cout<< str << std::endl;
}

以C++字符串作为参数的函数通常都带有char, 或者const char。这里给出的一小段程序显示了这两种方法的用法:

#include <cctype>
#include <iostream>

void makeUppercase(char *str)
{
 for(int i = 0; str[i] != '\0'; ++i)
 {
  str[i] = std::toupper(str[i]);
 }
}

void writeLine(const char* str)
{
 std::cout<< str << std::endl;i
}

int main(int argc, char* argv[])
{
 for(int i =1; i < argc; ++i)
 {
  makeUppercase(argv[i]);
  writeLine(argv[v]);
 }
 return 0;
}

在C++中,char类型通常保存为8位的值。这就是说,我们可以毫不费力地在一个char数组中存储ASCII,ISO 8859-1(Latin-1)以及其他采用8位编码的字符串,但是在没有使用多字节序列的情况下,就不能存储任意的Unicode字符。Qt提供了强大的QString类,它会把Unicode字符串存储为16位QChar,同时在内部还会使用隐式数据共享(“写时复制”)的优化技术。第11章和第18章曾经详细地介绍了QString类。

上一篇 下一篇

猜你喜欢

热点阅读