C/C++计算字符串最后一个单词的长度

C/C++计算字符串最后一个单词的长度

代码1

#include 
#include 
using namespace std;
// int str_length(char *s);
int main()
{
        char str[5000];
        cin.getline(str,4000);
        int length,temp=0;
        char *p1,*p2;
        length=strlen(str);
        p1=str;
        while(p1!=NULL&&(p1-str)<length)
            {
            if(*p1==str[0])
                {
                  p2=p1;
            while(*p2!=' '&&(p1-str)<length)
                {
                temp++;
                p2++;
                p1++;
            }
            }
                    if(*p1==' ')
            {
                    temp=0;
                p1++;
                p2=p1;
            while(*p2!=' '&&(p1-str)<length)
                {
                temp++;
                p2++;
                p1++;
            }
            } 
        }
        cout<

代码2

#include 
#include 
    using namespace std;
    int str_length(char *s);
    void main()
    {
        char str[130];
        int num, leng, i;
        cin.getline(str, 129);
        leng = strlen(str);
        //cout<
        for (i = 0; iif ((str[i] <= 'z'&&str[i] >= 'a') || (str[i] <= 'Z'&&str[i] >= 'A') || str[i] == ' ')
                str[i] = str[i];
            else
                str[i] = ' ';
        }

        num = str_length(str);
        cout << num << endl;
        while (1);
    }

    int str_length(char *s)
    {
        char *ptr1, *ptr2;
        int num = 0, temp, leng = strlen(s);
        if (s == NULL)
        {
            return 0;
        }
        else
        {
            ptr1 = s;
            ptr2 = NULL;
            while (ptr1 != NULL && (ptr1 - s)//若ptr1跑出s,则prt1-s大于等于leng
            {
                temp = 0;
                if (*ptr1 != ' ')
                {
                    ptr2 = ptr1;
                    while ((*ptr2) != ' ' && (ptr2 - s)return num;
        }   
}

代码3

#include
#include
using namespace std;
int main()
{
    char a[100];
    int n,i,count=0;
    cin.getline(a, 100);
    n = strlen(a);
    i = n - 1;
    while (a[i] != ' '&&i != 0)
    {
        count++;
        i--;
    }
    cout << count;

}

你可能感兴趣的:(c-c++面试题)