转帖:如何在C語言實現substr()?

(原創) 如何在C語言實現substr()? (C/C++) (C)

Posted on 2008-03-08 21:24 真 OO无双 阅读(2367) 评论(0)   编辑 收藏 网摘 所属分类: C/C++ C

Abstract
若要說處理字串什麼函數最常用,substr()應該會是前幾名,以我的經驗,C++、C#、VB、VFP、T-SQL都提供了substr(),好像C語言就沒提供這個函數,真的是這樣嗎?

Introduction
一個很簡單的需求,字串s為Hello World,希望從這個字串擷取World字串出來,若用C++,可以使用內建的substr(),但必須使用C++的std::string。

C++

1  /*  
2  (C) OOMusou 2008 http://oomusou.cnblogs.com
3 
4  Filename    : cpp_substr.cpp
5  Compiler    : Visual C++ 8.0
6  Description : Demo how to use substr() in C++
7  Release     : 03/08/2008 1.0
8  */
9  #include < iostream >
10  #include < string >
11 
12  using   namespace std;
13 
14  int main() {
15    string s =   " Hello World " ;
16    string t = s.substr( 6 , 5 );
17   
18    cout << t << endl;
19  }

執行結果

World


C++部分都很明顯直觀,就不多做說明了。

C語言

1  /*  
2  (C) OOMusou 2008 http://oomusou.cnblogs.com
3 
4  Filename    : c_substr.c
5  Compiler    : Visual C++ 8.0
6  Description : Demo how to use strncpy() in C
7  Release     : 03/08/2008 1.0
8  */
9  #include < stdio.h >
10  #include < string .h >
11 
12  int main() {
13    char s[] =   " Hello World " ;
14    char t[ 6 ];
15    strncpy(t, s +   6 , 5 );
16    t[ 5 ] =   0 ;
17    printf( " %s\n " , t);
18  }

執行結果

World


strncpy函數原型如下

char   * strncpy( char   * dest, const   char   * src, size_t n);


dest為目標字串,src為來源字串,n為複製的字數。所以我們可以去變動src的指標,這樣就可以用strncpy()來模擬substr()了,我想這也是為什麼C語言不提供substr()的原因,畢竟用strncpy()就可以簡單的模擬出來。

唯一比較討厭的是第16行

t[ 5 ] =   0 ;


因為strncpy()不保證傳回的一定是NULL terminated,所以要自己補0當結尾,這是C語言比較醜的地方,若覺得strncpy()用法很醜陋,可以自己包成substr()。

C語言

1  /*  
2  (C) OOMusou 2008 http://oomusou.cnblogs.com
3 
4  Filename    : c_substr.c
5  Compiler    : Visual C++ 8.0
6  Description : Demo how to use strncpy() in C
7  Release     : 03/08/2008 1.0
8  */
9  #include < stdio.h >
10  #include < string .h >
11 
12  void substr( char   * dest, const   char * src, unsigned int start, unsigned int cnt) {
13    strncpy(dest, src + start, cnt);
14    dest[cnt] =   0 ;
15  }
16 
17  int main() {
18    char s[] =   " Hello World!! " ;
19    char t[ 6 ];
20    substr(t, s, 6 , 5 );
21    printf( " %s\n " , t);
22  }

转载于:https://www.cnblogs.com/hecheng830/archive/2009/06/23/1509561.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值