C++ 在空格处拆分句子(字符串)

C++ 在空格处拆分句子(字符串),c++,string,C++,String,我试图将一个带有空格的字符串拆分为三个单独的字符串。例如,我有一个字符串(str1)。用户输入任意3个单词,例如 “嘿,是我”或“很热”。 从这里开始,我需要编写一个函数,将这个字符串(str1)分割成三个不同的字符串。因此(以第一个例子为例)它会说: Hey (is the first part of the string) it's (is the second part of the string) me (is the third part of the string) 我很难用哪种方

我试图将一个带有空格的字符串拆分为三个单独的字符串。例如,我有一个字符串(str1)。用户输入任意3个单词,例如
“嘿,是我”
“很热”
。 从这里开始,我需要编写一个函数,将这个字符串(str1)分割成三个不同的字符串。因此(以第一个例子为例)它会说:

Hey (is the first part of the string)
it's (is the second part of the string)
me (is the third part of the string)
我很难用哪种方法在空格处拆分字符串

这是到目前为止我所拥有的代码,这正是用户输入信息的方式。我正在寻找最基本的方法来实现这一点,而无需使用
istringstream
!仅使用基本的字符串操作,如find()、substr()

**我希望创建一个分离的函数来执行字符串的分解**我想出了如何使用以下代码获取输入的第一部分:

cout << "Enter a string" << endl;
getline(cin, one);

position = str1.find(' ', position);
first_section = str1.substr(0, position);
cout
我很难用哪种方法在空格处拆分字符串

  • 使用
    str1
    中的
    std::istringstream
  • std::istringstream
    读取每个令牌

  • //无需使用while循环,除非您希望这样做
    //多行的东西。
    //while(cin){
    cout>token2>>token3;
    //你想怎么用就怎么用
    // }
    

    如果您希望对多行输入执行相同的操作,请使用:

    int main() {
       string str1;
       cout << "Enter three words: ";
       while(getline(cin, str1))
       {
          cout << "Original string: " << str1 << endl;
          std::istringstream stream(str1);
          std::string token1;
          std::string token2;
          std::string token3;
    
          stream >> token1 >> token2 >> token3;
    
          // Use the tokens anyway you wish
    
          // Prompt the user for another line
          cout << "Enter three words: ";
       }
    }
    
    intmain(){
    字符串str1;
    cout token2>>token3;
    //你想怎么用就怎么用
    //提示用户输入另一行
    
    cout也许最基本的解决方案是使用循环中的内容来读取单个单词。例如:

    cin >> word1;       // extracts the first word
    cin >> word2;       // extracts the second word
    getline(cin, line); // extracts the rest of the line
    
    您可以使用这些表达式的结果或返回值来检查成功:

    #include <string>
    #include <iostream>
    
    int main(void) {
        std::string word1, word2, line;
        int success = std::cin >> word1 && std::cin >> word2
                                        && !!std::getline(std::cin, line); // double-! necessary?
        if (success) { std::cout << "GOOD NEWS!"  << std::endl; }
        else         { std::cout << "bad news :(" << std::endl; }
        return 0;
    }
    
    您可能应该对照
    string::npos
    检查这一点,以此作为处理错误的机会。接下来:

    size_t second_position = str1.find(' ', first_position + 1);
    
    下一个错误处理检查,然后使用它将字符串拆分为如下部分:

    size_t first_position  = str1.find(' ', 0);
    
    string first_section  = str1.substr(0              , first_position)
         , second_section = str1.substr(first_position , second_position)
         , third_section  = str1.substr(second_position, string::npos);
    

    我有一个实用程序类,它有一系列用于字符串操作的方法。我将展示使用分隔符拆分字符串的类函数。该类具有私有构造函数,因此您无法创建该类的实例。所有方法都是静态方法

    实用程序.h

    #ifndef UTILITY_H
    #define UTILITY_h
    
    // Library Includes Here: vector, string etc.
    
    class Utility {
    public:
        static std::vector<std::string> splitString( const std::string& strStringToSplit,
                                                     const std::string& strDelimiter,
                                                     const bool keepEmpty = true );
    
    private:
        Utility();
    };
    
    \ifndef实用程序
    #定义效用
    //这里的库包括:向量、字符串等。
    类效用{
    公众:
    静态标准::向量拆分字符串(常量标准::字符串和strStringTopSplit,
    常量标准::字符串和标准限制器,
    const bool keepmpty=true);
    私人:
    效用();
    };
    
    实用程序.cpp

    std::vector<std::string> Utility::splitString( const std::string& strStringToSplit, 
                                                   const std::string& strDelimiter, 
                                                   const bool keepEmpty ) {
        std::vector<std::string> vResult;
        if ( strDelimiter.empty() ) {
            vResult.push_back( strStringToSplit );
            return vResult;
        }
    
        std::string::const_iterator itSubStrStart = strStringToSplit.begin(), itSubStrEnd;
        while ( true ) {
            itSubStrEnd = search( itSubStrStart, strStringToSplit.end(), strDelimiter.begin(), strDelimiter.end() );
            std::string strTemp( itSubStrStart, itSubStrEnd );
            if ( keepEmpty || !strTemp.empty() ) {
                vResult.push_back( strTemp );
            }
    
            if ( itSubStrEnd == strStringToSplit.end() ) {
                break;
            }
    
            itSubStrStart = itSubStrEnd + strDelimiter.size();
        }
    
        return vResult;    
    } 
    
    std::vector实用工具::splitString(const std::string和strStringToSplit,
    常量标准::字符串和标准限制器,
    康斯特布尔(基彭普蒂){
    std::向量vResult;
    if(strDelimiter.empty()){
    vResult.推回(strStringToSplit);
    返回vResult;
    }
    std::string::const_迭代器itSubStrStart=strStringToSplit.begin(),itSubStrEnd;
    while(true){
    itSubStrEnd=搜索(itSubStrStart、STRSTRSTRINGTOSPLIT.end()、STRDELIMITORS.begin()、STRDELIMITORS.end());
    std::字符串strTemp(itSubStrStart,itSubStrEnd);
    if(keepEmpty | |!strTemp.empty()){
    vResult.推回(strTemp);
    }
    如果(itSubStrEnd==strStrStringTopSplit.end()){
    打破
    }
    itSubStrStart=itSubStrEnd+STRDELIMITOR.size();
    }
    返回vResult;
    } 
    
    Main.cpp--用法

    #包括
    #包括
    #包括“Utility.h”
    int main(){
    std::string myString(“你好,世界,你今天好吗”);
    std::vector vStrings=Utility::splitString(myString,“”);
    //检查字符串的向量
    for(无符号n=0;nSTD::你会考虑使用C函数来做吗?比如,代码> Strtok> <代码>?我严格地使用C++,在C++中有很多关于如何分割字符串的帖子,最简单的一个不需要你编写一个专门的函数来做它。在第一段字符串中,我得到一个错误,它说:[error]没有匹配的函数来调用'std::basic_string::substr(int,std::string&')@Alyssa你介意提供一些代码来演示这个问题吗?看起来你调用的是类似于
    str1.substr的东西(0,一些_string)
    其中
    某些字符串
    是错误的原因;您需要提供一个整数(
    size\t
    )值。不过,这只是一个猜测,如果没有您遇到问题的代码,我无法验证或使其无效。。。
    #ifndef UTILITY_H
    #define UTILITY_h
    
    // Library Includes Here: vector, string etc.
    
    class Utility {
    public:
        static std::vector<std::string> splitString( const std::string& strStringToSplit,
                                                     const std::string& strDelimiter,
                                                     const bool keepEmpty = true );
    
    private:
        Utility();
    };
    
    std::vector<std::string> Utility::splitString( const std::string& strStringToSplit, 
                                                   const std::string& strDelimiter, 
                                                   const bool keepEmpty ) {
        std::vector<std::string> vResult;
        if ( strDelimiter.empty() ) {
            vResult.push_back( strStringToSplit );
            return vResult;
        }
    
        std::string::const_iterator itSubStrStart = strStringToSplit.begin(), itSubStrEnd;
        while ( true ) {
            itSubStrEnd = search( itSubStrStart, strStringToSplit.end(), strDelimiter.begin(), strDelimiter.end() );
            std::string strTemp( itSubStrStart, itSubStrEnd );
            if ( keepEmpty || !strTemp.empty() ) {
                vResult.push_back( strTemp );
            }
    
            if ( itSubStrEnd == strStringToSplit.end() ) {
                break;
            }
    
            itSubStrStart = itSubStrEnd + strDelimiter.size();
        }
    
        return vResult;    
    } 
    
    #include <string>
    #include <vector>
    #include "Utility.h"
    
    int main() {
        std::string myString( "Hello World How Are You Today" );
    
        std::vector<std::string> vStrings = Utility::splitString( myString, " " );
    
        // Check Vector Of Strings
        for ( unsigned n = 0; n < vStrings.size(); ++n ) {
            std::cout << vStrings[n] << " ";
        }
        std::cout << std::endl;
    
        // The Delimiter is also not restricted to just a single character
        std::string myString2( "Hello, World, How, Are, You, Today" );
    
        // Clear Out Vector
        vStrings.clear();
    
        vStrings = Utility::splitString( myString2, ", " ); // Delimiter = Comma & Space
    
        // Test Vector Again
        for ( unsigned n = 0; n < vStrings.size(); ++n ) {
            std::cout << vStrings[n] << " ";
        }
        std::cout << std::endl;
    
        return 0;
    }