簡體   English   中英

在 C++ 中用其大小打印字符串中的第二個單詞

[英]print 2nd word in a string with its size in C++

我正在嘗試制作一個用戶輸入字符串的程序,我將打印出字符串中的第二個單詞及其大小。 分隔符是空格( )、逗號(,) 和制表符( )。 我使用了一個字符數組和 fgets 來讀取用戶和一個指向數組第一個元素的字符指針。

源代碼:

#include"iostream"
#include<stdio.h>
#include<string>

using namespace std;

// extract the 2nd word from a string and print it with its size(the number of characters in 2nd word)

int main()
{
    char arr[30], arr1[30];
    char *str = &arr1[0];

    cout<<"Enter a string: ";
    fgets(str, 30, stdin);

    int i = 0, j, count = 1, p = 0;     // count is used to find the second word
    // j points to the next index where the first delimiter is found.
    // p is used to store the second word found in character array 'arr'

    while(*(str+i) != '\n')
    {
        if(*(str+i) == ' ' || *(str+i) == ',' || *(str+i) == '  ')
        {
            count++;

            if(count == 2)
            {
                // stroing 2nd word in arr character array
                j = i+1;    
                while(*(str+j) != ' ' || *(str+j) != ',' || *(str+j) != '   ')
                {
                    arr[p] = *(str+j);
                    cout<<arr[p];
                    p++;
                    i++;
                    j++;
                }
                break;
            }

        }
        i++;
    }

    arr[p+1] = '\0';        // insert NULL at end

    i = 0;
    while(arr[i] != '\0')
    {
        cout<<arr[i];
        i++;
    }

    cout<<"("<<i<<")"<<endl;

    return 0;
}

幫我解決這個問題。

從流中提取時使用的分隔符取決於當前有效的locale 更改提取行為的一種(麻煩的)方法是創建一個具有特殊facet的新區域設置,您可以在其中指定自己的分隔符。 在下面的示例中,新的語言環境用於直接注入std::stringstream而不是std::cin 構面創建部分主要是從 SO 上的其他答案復制/粘貼,因此您會找到很多其他示例。

#include <iostream>
#include <locale>    // std::locale, std::ctype<char>
// https://en.cppreference.com/w/cpp/locale/ctype_char
#include <sstream>   // std::stringstream
#include <algorithm> // std::copy_n
#include <vector>    // a container to store stuff in

// facet to create our own delimiters
class my_facet : public std::ctype<char> {
    mask my_table[table_size];
public:
    my_facet(size_t refs = 0)
        : std::ctype<char>(&my_table[0], false, refs)
    {
        // copy the "C" locales table to my_table
        std::copy_n(classic_table(), table_size, my_table);
        // and create our delimiter specification
        my_table[' '] = (mask)space;
        my_table['\t'] = (mask)space;
        my_table[','] = (mask)space;
    }
};

int main() {
    std::stringstream ss;
    // create a locale with our special facet
    std::locale loc(std::locale(), new my_facet);
    // imbue the new locale on the stringstream
    ss.imbue(loc);

    while(true) {
        std::string line;
        std::cout << "Enter sentence: ";
        if(std::getline(std::cin, line)) {
            ss.clear(); // clear the string stream from prior errors etc.
            ss.str(line); // assign the line to the string stream

            std::vector<std::string> words; // std::string container to store all words in
            std::string word; // for extracting one word

            while(ss>>word) { // extract one word at a time using the special facet
                std::cout << "  \"" << word << "\" is " << word.size() << " chars\n";
                // put the word in our container
                words.emplace_back(std::move(word));
            }
            if(words.size()>=2) {
                std::cout << "The second word, \"" << words[1] << "\", is " << words[1].size() << " chars\n";
            } else {
                std::cout << "did not get 2 words or more...\n";
            }
        } else break;
    }
}

首先,不要使用std::cin進行測試。 只需在您的代碼中設置一個值即可實現一致性和易於開發。 使用此頁面作為參考。

#include <iostream>
#include <string>

int main() {
    std::string str("this and_that are the tests");
    auto start = str.find_first_of(" ,\n", 0);
    auto end = str.find_first_of(" ,\n", start + 1);
    std::cout << str.substr(start, end - start);
    return 0;
}

這仍然有點像黑客,這取決於你要去哪里。 例如,Boost 庫具有豐富的擴展字符串操作。 如果您要解析的不僅僅是一個單詞,它仍然可以通過字符串操作來完成,但臨時解析器可能會失控。 還有其他工具,例如Boost Spirit,可以控制代碼。

#include"iostream"
#include<stdio.h>
#include<string>
#include <ctype.h>

using namespace std;


int main()
{
    char c;
    string str;
    char emp = ' ';
    cout<<"Enter a string: ";
    getline (cin,str);


    int  j = 0, count = 1, counter = 0;  


    for (int i = 0; i < str.length() && count != 2; i++)
    {
        cout<< str[i] <<endl;
        if( isspace(str[i]) || str[i] == ',' || str[i] == '\t' )
        {
            count++;

            if(count == 2)
            {
                j = i+1;
                while(j < str.length())
                {
                    if (isspace(str[j]) || str[j] == ',' || str[j] == '\t')
                    {
                        break;

                    }
                    cout<<str[j];
                    counter++;
                    j++;
                }
                cout<<endl;
            }

        }
    }



    cout<<"size of the word: "<<counter<<endl;

    return 0;


}

這是您想要的簡單答案,希望對您有所幫助。

// Paul Adrian P. Delos Santos - BS Electronics Engineering
// Exercise on Strings

#include <iostream>
#include <sstream>

using namespace std;

int main(){
    
    // Opening Message
    
    cout << "This program will display the second word and its length.\n\n";
    
    // Ask for a string to the user.
        
    string input;   
    cout << "Now, please enter a phrase or sentence: ";
    getline(cin, input);
    
    // Count the number of words to be used in making a string array.
    
    int count = 0;
    int i;
    
    for (i=0; input[i] != '\0'; i++){
        if (input[i] == ' ')
            count++;        
    }
    
    int finalCount = count + 1;
    
    // Store each word in a string array.
    
    string arr[finalCount];
   
    int j = 0;
    stringstream ssin(input);
   
    while (ssin.good() && j < finalCount){
        ssin >> arr[j];
        j++;
    }
    
    // Display the second word and its length. 
    
    string secondWord = arr[1];
    
    cout << "\nResult: " << arr[1] << " (" << secondWord.size() << ")";
    
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM