C++ 中的 string__npos 及其示例


在本文中,我們將深入探討 C++ 字串處理的特定方面:string::npos 常量。string::npos 是一個靜態成員常量值,它具有 size_t 型別元素的最大可能值。此常量定義為 -1,當轉換為 size_t 時,它會為我們提供 size_t 的最大可能表示形式。在 C++ 字串的上下文中,它通常用於指示無效位置。

什麼是 String::npos?

在 C++ 中,string::npos 是 std::string 類的常量靜態成員,它表示 size_t 型別的最大可能值。它通常用於表示字串的結尾,或者表示在另一個字串中找不到子字串或字元。

String::npos 的用例

string::npos 的主要用例之一是與 std::string::find 函式一起使用。此函式返回字串中子字串第一次出現的 位置。如果找不到子字串,則該函式返回 std::string::npos。

示例

讓我們透過一個簡單的 C++ 示例來了解其工作原理:

#include <iostream>
#include <string>

int main() {
   std::string str = "Hello, World!";
   size_t found = str.find("World");
   
   if (found != std::string::npos)
      std::cout << "'World' found at: " << found << '\n';
   else
      std::cout << "'World' not found\n";
      
   found = str.find("Earth");
   
   if (found != std::string::npos)
      std::cout << "'Earth' found at: " << found << '\n';
   else
      std::cout << "'Earth' not found\n";
   
   return 0;
}

輸出

'World' found at: 7
'Earth' not found

在此示例中,程式嘗試在字串“Hello, World!”中查詢子字串“World”和“Earth”。對於“World”,find 函式返回第一次出現的 位置,即 7。對於“Earth”,find 函式返回 string::npos,因為在字串中找不到“Earth”,指示無效位置。

結論

string::npos 是 C++ 字串操作的有用常量,尤其是在使用 find 等可能返回無效位置的函式時。瞭解如何在 C++ 程式中使用 string::npos 來有效地處理字串非常重要。

更新於: 2023-05-18

1K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.