Discusses writing int strlen (char *strdest); Problems with defining variables _c language

Source: Internet
Author: User
Tags assert strlen
In the forum to see a predecessor of the face of the question, the exact words are said "One of the problems encountered during the interview was that it was not allowed to call the library function, and it was not allowed to write int strlen (char *strdest) with any global or local variables; ", inadvertently see, they think for a while, no ideas, and then sorted out the reply to the cattle, I think the use of recursive method to solve this problem, is a very good way! So, a little bit of writing code, is a bit of a pioneering vision of accumulation bar!
Copy Code code as follows:

#include "stdafx.h"
#include <iostream>
#include <assert.h>//Use Assert Assert header file
using namespace Std;
Common method.
int Mystrlen (const char* strdest)
{
ASSERT (NULL!= strdest); The assertion is used, and if strdest is NULL, the program is terminated
int i (0);
while ('!= ' *strdest)//The flag that determines the end of the string, ' the ' is ' identifier
{
i + +;
Strdest + +;
}
return i;
}
Recursive method, no new global and local variables defined
int MyStrlen2 (const char* strdest)
{
ASSERT (null!= strdest);/use assertion, if strdest is NULL, terminate program
if ('!= ' *strdest)
{
Return 1 + MyStrlen2 (++strdest);
}
Else
{
return 0;
}
}
Similar to the above method, only the question mark expression used
int MyStrlen3 (const char* strdest)
{
ASSERT (null!= strdest);/use assertion, if strdest is NULL, terminate program
Return ('!= ' *strdest)?  (1 + MyStrlen3 (++strdest)): 0; At this time i++ and ++i difference value manifests, strdest++ not, consider why?
}
int _tmain (int argc, _tchar* argv[])
{
Char a[] = {"Hello world!"};
cout << Mystrlen (a) << Endl;
cout << MyStrlen2 (a) << Endl;
cout << MyStrlen3 (a) << Endl;
return 0;
}

Attention: ++strdest can not be replaced by strdest++, at this time i++ and ++i the difference between the value embodied, strdest++ not, consider why?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.