不使用庫函數編寫strlen函數

來源:互聯網
上載者:User

不使用庫函數,甚至不使用變數來寫出strlen函數,或者字串的其他函數是筆試、面試等中經常會遇到的一個問題。

下面貼出代碼分享。

#include <stdio.h>#include <stdlib.h>#include <string.h>int my_strlen1(const char *str)//遞迴{return ('\0' != *str) ? (1+my_strlen1(++str)) : 0;}int my_strlen2(const char *str)//迭代{int count = 0;while (*str != '\0'){count++;str++;}return count;}int main(){char *p;p = (char *)malloc(100*sizeof(char));while (scanf("%s",p) != EOF){int count1 = 0,count2 = 0,count3 = 0;count1 = my_strlen1(p);count2 = my_strlen2(p);count3 = strlen(p);printf("count1 = %d, count2 = %d, coont3 = %d\n",count1,count2,count3);}free(p);return 0;}

my_strlen1函數採用的是遞迴策略,沒有使用任何變數。編寫遞迴時要考慮遞迴深度,有時會造成棧溢出。

my_strlen2函數採用簡單的迭代,容易理解。

 

還有其他類型的,比如,不使用庫函數寫出兩個字串串連的函數,字串比較的函數等等。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.