C Language Implementation strlen () 4 Methods and strcat () 3 ways

Source: Internet
Author: User

#include <stdio.h> #include <assert.h> #if 0//default method 4//1 int strlen (const char* str) {int N;//const char *p = s Tr To test this sentence, this statement does not need to be, because my argument is a pointer, the parameter pointer changes to point to not affect the argument pointing to for (n = 0; *str! = ') '; n++) {str++;} return n;} #elif 0//Method 2 int strlen (const char* str) {int n = 0;for (; *str++; n++); return n;} #elif 0//Method 3 int strlen (const char* STR) {int n = 0;while (*str++) {n++;} return n;} #else//Method 4 int strlen (const char* str) {const char *p =str;while (*STR)//write while (*str++) not (because Str is added at return, 1 more), Must be written in the current code, str++; return str-p;} #endif #if 0char* strcat (char* str1, const char* str2) {assert ((str1!=null) && (str2!=null));//if ((str1==null) | | (Str2==null)) Throw "Invalide arguments!"; Char *p = str1;while (*p! = ') p++;while (*str2! = ') ' {*p = *str2;//error p++;str2++ occurred here;} *p = ' + '; return str1;} #elif 0char* strcat (char* str1,const char* str2) {assert ((str1!=null) && (str2!=null));//if ((str1==null) | | (Str2==null)) Throw "Invalide arguments!"; Char *p = str1;while (*p)//is written as a while (*p++) error for the reason that P++; while (*p++ = *str2++); return str1;}    #elsechar *strcat (Char *dst, char *src) {size_t Dst_len = strlen (DST);    int i;           for (i = 0; Src[i]! = ' + '; i++) Dst[dst_len + i] = src[i];    Dst[dst_len + i] = ' + '; return (DST);} #endifint Main (int argc, char **argv) {/* s best be large enough, otherwise overflow, here can be compiled and run, but do not do so */char s1[] = "AB";//Use char * = "AB", *s3 = "CDE";    Raw segment Error char s2[] = "CDE"; int len;strcat (S1,S2);    Len = strlen (S1); printf ("S1 =%s\n", s1);p rintf ("len =%d\n", len); return 0;}

Output:


C Language Implementation strlen () 4 Methods and strcat () 3 ways

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.