c语言 substr,如何在C语言实现substr()

若要说处理字串什么函数最常用,substr()应该会是前几名,以我的经验,C++、C#、VB、VFP、T-SQl都提供了substr(),好像C语言就没提供这个函数,真的是这样吗? Introduction 一个很简单的需求,字串s为Hello World,希望从这个字串截取World字串处理,若

若要说处理字串什么函数最常用,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

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

10 #include

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

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

10 #include

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("%sn", 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

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

10 #include

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("%sn", t);

22 }

执行结果

World

这样就漂亮多了,程序我就不再多做解释了。

Conclusion

原本以为C语言没有提供substr(),却意外发现竟然有个很类似的strncpy(),所以真的不能小看C语言,,在订定标准时,其实都要考虑到了。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值