请教华为的一个上机题,字符串最后一个单词的长度

C++语言 码拜 8年前 (2016-06-06) 1033次浏览
题目如下:
请教华为的一个上机题,字符串最后一个单词的长度
本人的代码:
#include <iostream>
#include <cstring>
using namespace std;
int str_length(char *s);
void main()
{
char str[139];
int num;
cout<<“please input a string:\n”;
cin.getline(str,129);
num=str_length(str);
cout<<num<<endl;
}
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)<leng)  //若ptr1跑出s,则prt1-s大于等于leng
{
temp=0;
if(*ptr1!=” “)
{
ptr2=ptr1;
while((*ptr2)!=” “&&(ptr2-s)<leng)
{
temp++;
ptr2++;
}
ptr1=ptr2;
}
if(temp!=0)
{
num=temp;  //
}
ptr1++;
}
return num;
}
}
本人在vs上运行可以出来正确结果,但是显示程序测试用例未完全通过,帮看看本人忽略了哪些情况。
解决方案

20

本人就想知道
from 1 to 100
这种应该返回几
this is a serial number ASDF_GHJK_QWER_TYUI_ZXCV
这种应该返回几
this is a password !QAZ2wsx#EDC
这种应该返回几

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明请教华为的一个上机题,字符串最后一个单词的长度
喜欢 (0)
[1034331897@qq.com]
分享 (0)