ㄚ琪發現常用PHP寫web程式很容易變笨,這會想用C寫支程式轉檔後存MySQL資料庫,卻發現連substr的功能都沒有,Orz~後來ㄚ琪看到(原創) 如何在C語言實現substr()? (C/C++) (C)才發現可以自己動手寫substr的函數,給他棒棒一下。
Abstract
若要說處理字串什麼函數最常用,substr()應該會是前幾名,以我的經驗,C++、C#、VB、VFP、T-SQL都提供了substr(),好像C語言就沒提供這個函數,真的是這樣嗎?
哥的C# substring的文章可以參考→C# Substring 定義及七種用法。
※2020/12/11 這真的詭異了,Google 『c substring』 還是會找到上面的文章,原本的這篇在C語言實現substr()找不到了。
就連ㄚ琪常用的PHP、perl、Python跟ASP也都有啊。
Introduction
/* (C) OOMusou 2008 http://oomusou.cnblogs.com Filename : c_substr.c Compiler : Visual C++ 8.0 Description : Demo how to use strncpy() in C Release : 03/08/2008 1.0 */ #include < stdio.h > #include < string .h > int main() { char s[] = " Hello World " ; char t[ 6 ]; strncpy(t, s + 6 , 5 ); t[ 5 ] = 0 ; printf( " %s\n " , t); }
執行結果
strncpy函數原型如下
dest為目標字串,src為來源字串,n為複製的字數。所以我們可以去變動src的指標,這樣就可以用strncpy()來模擬substr()了,我想這也是為什麼C語言不提供substr()的原因,畢竟用strncpy()就可以簡單的模擬出來。
唯一比較討厭的是
因為strncpy()不保證傳回的一定是NULL terminated,所以要自己補0當結尾,這是C語言比較醜的地方,若覺得strncpy()用法很醜陋,可以自己包成substr()。
C語言
/* (C) OOMusou 2008 http://oomusou.cnblogs.com Filename : c_substr.c Compiler : Visual C++ 8.0 Description : Demo how to use strncpy() in C Release : 03/08/2008 1.0 */ #include < stdio.h > #include < string .h > void substr( char * dest, const char * src, unsigned int start, unsigned int cnt) { strncpy(dest, src + start, cnt); dest[cnt] = 0 ; } int main() { char s[] = " Hello World!! " ; char t[ 6 ]; substr(t, s, 6 , 5 ); printf( " %s\n " , t); }
執行結果
這樣就漂亮多了,程式碼我就不再多做解釋了。
Conclusion
原本以為C語言沒有提供substr(),卻意外發現竟然有個很類似的strncpy(),所以真的不能小看C語言,在訂定標準時,其實都有考慮到了。