在 C++ 中宣告多行字串

Jinku Hu 2023年1月30日 2021年1月4日
  1. 使用 std::string 類在 C++ 中宣告多行字串
  2. 使用 const char *符號來宣告多行字串文字
  3. 使用 const char *符號與反斜槓字宣告多行字串文字
在 C++ 中宣告多行字串

本文將介紹幾種在 C++ 中如何宣告多行字串的方法。

使用 std::string 類在 C++ 中宣告多行字串

std::string 物件可以用一個字串值初始化。在這種情況下,我們將 s1 字串變數宣告為 main 函式的一個區域性變數。C++ 允許在一條語句中自動連線多個雙引號的字串字元。因此,在初始化 string 變數時,可以包含任意行數,並保持程式碼的可讀性更一致。

#include <iostream>
#include <string>
#include <vector>
#include <iterator>

using std::cout; using std::vector;
using std::endl; using std::string;
using std::copy;

int main(){
    string s1 = "This string will be printed as the"
                " one. You can include as many lines"
                "as you wish. They will be concatenated";

    copy(s1.begin(), s1.end(),
         std::ostream_iterator<char>(cout, ""));
    cout << endl;

    return EXIT_SUCCESS;
}

輸出:

This string will be printed as the one. You can include as many linesas you wish. They will be concatenated

使用 const char *符號來宣告多行字串文字

但在大多數情況下,用 const 修飾符宣告一個只讀的字串文字可能更實用。當相對較長的文字要輸出到控制檯,而且這些文字大多是靜態的,很少或沒有隨時間變化,這是最實用的。需要注意的是,const 限定符的字串在作為 copy 演算法引數傳遞之前需要轉換為 std::string 物件。

#include <iostream>
#include <string>
#include <vector>
#include <iterator>

using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::copy;

int main(){
    const char *s2 =
            "This string will be printed as the"
            " one. You can include as many lines"
            "as you wish. They will be concatenated";

    string s1(s2);

    copy(s1.begin(), s1.end(),
         std::ostream_iterator<char>(cout, ""));
    cout << endl;

    return EXIT_SUCCESS;
}

輸出:

This string will be printed as the one. You can include as many linesas you wish. They will be concatenated

使用 const char *符號與反斜槓字宣告多行字串文字

另外,也可以利用反斜槓字元/來構造一個多行字串文字,並將其分配給 const 限定的 char 指標。簡而言之,反斜槓字元需要包含在每個換行符的末尾,這意味著字串在下一行繼續。

不過要注意,間距的處理變得更容易出錯,因為任何不可見的字元,如製表符或空格,可能會將被包含在輸出中。另一方面,人們可以利用這個功能更容易地在控制檯顯示一些模式。

#include <iostream>
#include <string>
#include <vector>
#include <iterator>

using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::copy;

int main(){
    const char *s3 = "          This string will\n\
        printed as the pyramid\n\
    as one single string literal form\n";

    cout << s1 << endl;

    printf("%s\n", s3);

    return EXIT_SUCCESS;
}

輸出:

          This string will
        printed as the pyramid
    as one single string literal form
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相關文章 - C++ String