溫馨提示×

Linux中C++如何進行字符串處理

小樊
41
2025-09-13 05:56:22
欄目: 編程語言

在 Linux 中,C++ 可以使用標準庫 <string><cstring> 進行字符串處理。以下是一些常用的字符串處理方法:

  1. 包含頭文件:
#include <iostream>
#include <string>
#include <cstring>
  1. 創建字符串:
std::string str1 = "Hello, World!";
const char* str2 = "Hello, C++!";
  1. 字符串長度:
size_t len1 = str1.length();
size_t len2 = strlen(str2);
  1. 字符串連接:
std::string str3 = str1 + " " + str2;
  1. 字符串比較:
int result = str1.compare(str2); // 返回負數表示 str1 < str2,0 表示相等,正數表示 str1 > str2
  1. 查找子字符串:
size_t pos = str1.find("World"); // 返回子字符串 "World" 在 str1 中的位置,如果找不到則返回 std::string::npos
  1. 替換子字符串:
std::string str4 = str1.replace(pos, 5, "Linux"); // 將 str1 中從位置 pos 開始的 5 個字符替換為 "Linux"
  1. 分割字符串:
#include <sstream>
#include <vector>

std::istringstream iss(str1);
std::string word;
std::vector<std::string> words;
while (iss >> word) {
    words.push_back(word);
}
  1. 字符串轉換:
int num = std::stoi(str1); // 將字符串 str1 轉換為整數
double dbl = std::stod(str1); // 將字符串 str1 轉換為浮點數
std::string str5 = std::to_string(num); // 將整數 num 轉換為字符串

這些只是 C++ 字符串處理的一部分功能。你可以根據需要使用其他 <string><cstring> 庫中的函數。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女