
ㄚ琪發現常用PHP寫web程式很容易變笨,這會想用C寫支程式轉檔後存MySQL資料庫,卻發現連substr的功能都沒有,Orz~後來ㄚ琪看到(原創) 如何在C語言實現substr()? (C/C++) (C)才發現可以自己動手寫substr的函數,給他棒棒一下。
Abstract
若要說處理字串什麼函數最常用,substr()應該會是前幾名,以我的經驗,C++、C#、VB、VFP、T-SQL都提供了substr(),好像C語言就沒提供這個函數,真的是這樣嗎?
哥的C# string substring的文章可以參考→C# Substring 定義及七種用法。
※2020/12/11 這真的詭異了,Google 『c substring』 還是會找到上面的文章,原本的這篇在C語言實現substr()找不到了。
就連ㄚ琪常用的PHP、perl、Python跟ASP也都有啊。
Introduction
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 >
int main() {
char s[] = " Hello World " ;
char t[ 6 ];
strncpy(t, s + 6 , 5 );
t[ 5 ] = 0 ;
printf( " %sn " , 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( " %sn " , t);
}
執行結果
這樣就漂亮多了,程式碼我就不再多做解釋了。
Conclusion
原本以為C語言沒有提供substr(),卻意外發現竟然有個很類似的strncpy(),所以真的不能小看C語言,在訂定標準時,其實都有考慮到了。
※2022/02/24
今天在D 棧-DelftStack看到了《如何在 C 語言中獲取子字串》這篇文章,裡頭有 memcpy()這個函式也可以做substring,底下節錄作法給各位學習:
memcpy() 函式將原始檔中的字元數複製到目標檔案的記憶體區。這個函式在 <string.h> 標頭檔案中可用。
當來源位址和目標位址重疊時,這個函式會產生問題。這個函式不檢查位址是否為空,也不檢查是否發生溢位。
memcpy() 函式返回一個指向目標字串的指標。沒有返回值來顯示錯誤。
memcpy() 的語法
void *memcpy(void *destination_string, const void *source_string, size_t number);
destination_string是指向目標字串的指標。source_string是指向原始字元型別值陣列的指標。number是字元數。
#include <stdio.h>
#include <string.h>
int main(void)
{
char *text = "The test string is here";
char subtext[7];
memcpy(subtext,&text[9],6);
subtext[6] = '0';
printf("The original string is: %sn",text);
printf("Substring is: %s",subtext);
return 0;
}
輸出:
The original string is: The test string is here
Substring is: string
★編譯器資源
- 編譯器
- 設定C和C++ Code::Blocks編譯器的初學者教學指南:如果你苦惱的是編譯器的使用,可以看看設定C和C++ Code::Blocks編譯器的初學者教學指南。
- Code::Blocks 13.12 繁體中文化:如果想要使用code block 中文的朋友可以繼續閱讀Code::Blocks 13.12 繁體中文化,這裡不會有code block中文亂碼的問題。
- 設定Dev-C++ 5.11和MinGW-w64, Windows上免費的C跟C++編譯器
- C跟C++的Apple XCode
- g++簡介
- 使用Microsoft Visual C++ 2010 Express編譯GTK+
- Eclipse+CDT+MinGW 安裝測試
- 編譯器gcc
- Code::Blocks 20.03的安裝設定及繁體中文化
或者完全看不懂大叔在寫什麼,那麼推薦你去好學校上C 語言入門特訓,祝福你
有關c++ substr的使用可以參考C++全方位學習第四版(適用Dev C++與Visual C++),本書第一版榮獲國家圖書館狀元推薦閱讀書單科學類第15名,也是唯二進榜的程式設計書籍,也可以參考我們從微軟文件節錄出來的c++ substr及c++常用七種字串函數
順便看看 資料庫正規化、MySQL 流程控制的迴圈
4 則留言