溫馨提示×

stringstream如何解析字符串

小樊
81
2024-10-16 14:48:12
欄目: 編程語言

stringstream 是 C++ 中的一個類,它位于 <sstream> 庫中。這個類允許你使用流操作符 <<>> 來讀取和寫入字符串。你可以使用 stringstream 來解析字符串,例如提取子字符串、轉換數(shù)據(jù)類型等。

下面是一些使用 stringstream 解析字符串的例子:

  1. 提取子字符串:
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string input = "Hello, my name is John Doe.";
    std::stringstream ss(input);
    std::string name;

    // 提取名字
    getline(ss, name, ' '); // 使用空格作為分隔符
    std::cout << "Name: " << name << std::endl;

    return 0;
}
  1. 轉換數(shù)據(jù)類型:
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string input = "123 45.67";
    std::stringstream ss(input);
    int age;
    double salary;

    // 轉換整數(shù)和浮點數(shù)
    ss >> age >> salary;
    std::cout << "Age: " << age << ", Salary: " << salary << std::endl;

    return 0;
}
  1. 解析逗號分隔的值:
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string input = "apple,banana,orange";
    std::stringstream ss(input);
    std::string fruit;

    // 使用逗號作為分隔符
    while (getline(ss, fruit, ',')) {
        std::cout << "Fruit: " << fruit << std::endl;
    }

    return 0;
}

這些例子展示了如何使用 stringstream 來解析字符串。你可以根據(jù)需要調整分隔符和數(shù)據(jù)類型,以便正確地解析你的字符串。

0