5

我编写的这段代码逐个字符地循环遍历字符串。我想要的是逐字循环遍历字符串。这是我的代码。

string a; // already declared
   // c is string array
for (i=0;i<b;i++) {
    if (strcmp (c[i],a[i]) == 0 ) {
      // do something
       }
     }
4

2 回答 2

11

您可以使用字符串流:

string a = "hello   my name    is    joe";
stringstream s(a);
string word;
// vector<string> c = ... ;

for (int i = 0; s >> word; i++)
{
    if (word == c[i])
    {
        // do something
    }
}

如果您希望能够在单词中前后移动,您应该将它们存储在一个数组中,因此第二个代码对此很有用:

string a = "hello   my name    is    joe";
vector<string> c = {"hello","my","name","is","joe"};
string word;
vector<string> words;

for (stringstream s(a); s >> word; )
    words.push_back(word);

for (int i=0; i<words.size(); i++)
{
    if (words[i] == c[i])
    {
        // do something
    }
}
于 2013-11-10T07:21:41.893 回答
-1

检查这个:

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

using namespace std;

void sort(int *,int);

int word_size(char * in, int length)
{
    int size = 0;
    if(!strcmp(in,""))
        size = 1;

    for(int i =0 ;i<length;i++)
    {
        if(in[i] == ' ')
            size ++;
    }

    return size;
}

int get_word_size(char * in,int length, int index)
{
    int word_num = 0;
    int size = 0;

    for(int i = 0;i<length;i++)
    {
        if(in[i] == ' ')
            word_num++;
        else if(word_num == index)
        {
            size++;
        }
    }
    return size;
}

char * get_word(char * in,int length,int index)
{
    char * result = new char[get_word_size(in,length,index)];
    int k = 0;
    int word_num = 0;

    for(int i = 0;i<length;i++)
    {
        if(in[i] == ' ')
            word_num++;
        else if(word_num == index)
        {
            result[k] = in[i];
            k++;
        }
    }

    return result;
}

int _tmain(int argc, _TCHAR* argv[])
{
    char * x = "Hello this is my name";


    char * y = "byebye that was your name";



    char * outChar = get_word(x,21,3);
    outChar[get_word_size(x,21,2)] = '\0';
    cout << outChar;

    int a;
    cin>>a;
    return 0;
}

刚刚测试了一下...

于 2013-11-10T07:57:32.580 回答