在C语言实现substr()

ㄚ琪发现常用PHP写web程式很容易变笨,这会想用C写支程式转档后存MySQL资料库,却发现连substr的功能都没有,Orz~后来ㄚ琪看到(原创) 如何在C语言实现substr()? (C/C++) (C)才发现可以自己动手写substr的函数,给他棒棒一下。

[adsense][/adsense]

Abstract
若要说处理字串什么函数最常用,substr()应该会是前几名,以我的经验,C++、C#、VB、VFP、T-SQL都提供了substr(),好像C语言就没提供这个函数,真的是这样吗?

就连ㄚ琪常用的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(“%s\n”, t);
}

执行结果

World

strncpy函数原型如下

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

dest为目标字串,src为来源字串,n为复制的字数。所以我们可以去变动src的指标,这样就可以用strncpy()来模拟substr()了,我想这也是为什么C语言不提供substr()的原因,毕竟用strncpy()就可以简单的模拟出来。

唯一比较讨厌的是

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 }

执行结果

World

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

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