简体   繁体   English

如何从由空格分隔的单个字符串中提取多个子字符串?

[英]how do i extract multiple substrings from a single string separated by space?

i was trying to solve this problem https://a2oj.com/p?ID=24 我正在尝试解决此问题https://a2oj.com/p?ID=24

my initial code (only testing the input part) 我的初始代码(仅测试输入部分)

#include<iostream>
using namespace std;

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int l;
        string input;
        cin>>l>>input;

        string texts[l];

        int c=0;
        for(int i=0;i<input.size();i++)
        {
            if(input[i]==' ')
                {c++;continue;}
            else
            {
                texts[c]=texts[c]+input[i];
            }
        }

        for(int i=0;i<l;i++)
            cout<<texts[i]<<endl;
    }
    return 0;
}

its only scanning until it receives first ' '(space), and not other sub strings. 直到接收到第一个''(空格),而不接收其他子字符串为止。

You can use getline(); 您可以使用getline();

in this code i've used 't' as delimeter you can use space " " or whatever you want 在这段代码中,我使用了“ t”作为分隔符,您可以使用空格“”或任何您想要的

Example code 范例程式码

#include <iostream.h>

void main()
{
   char line[100];
   cout << " Type a line terminated by 't'" << endl;
   cin.getline( line, 100, 't' );
   cout << line;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM