hecheng8330

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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 }

posted on 2009-06-23 15:56  hecheng8330  阅读(2379)  评论(0编辑  收藏  举报