李sir_Blog

博客园 首页 联系 订阅 管理
  705 随笔 :: 58 文章 :: 134 评论 :: 193万 阅读

Abstract
寫過JavaScript或ASP的朋友,應該常常用到split()這個函數,他可以輕易地將string轉成array,C語言並沒有相對應的函數,只有strtok()較為接近,稍微加工後,就可以在C語言實現split()。

Introduction
使用環境 : IE 7.0 + Visual Studio 2008

在JavaScript,可以輕易的將string轉成array。

split.htm / JavaScript

复制代码
1 <!-- 
2 (C) OOMusou 2009 http://oomusou.cnblogs.com
3 
4 Filename    : split.htm
5 Compiler    : IE 7.0
6 Description : javaScript's split()
7 Release     : 05/09/2009
8 -->
9 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
10 <html xmlns="http://www.w3.org/1999/xhtml">
11 <head>
12   <script language="javascript" type="text/javascript">
13     function Button1_onclick() {
14       str = "10,20,30";
15       arr = str.split(",");
16      
17       for(i=0; i < 3; i++)
18         document.getElementById("div1").innerHTML += arr[i] + "<br>";
19     }
20   </script>
21 </head>
22 <body>
23   <input id="Button1" type="button" value="button" onclick="return Button1_onclick()" />
24   <div id="div1">
25   </div>
26 </body>
27 </html>
复制代码


split.c / C

复制代码
1 /* 
2 (C) OOMusou 2009 http://oomusou.cnblogs.com
3 
4 Filename    : split.c
5 Compiler    : Visual C++ 9.0
6 Description : Demo how to implement split() in C
7 Release     : 05/09/2009 1.0
8 */
9 
10 #include <stdio.h>
11 #include <string.h>
12 
13 void split(char **arr, char *str, const char *del) {
14   char *s = strtok(str, del);
15  
16   while(s != NULL) {
17     *arr++ = s;
18     s = strtok(NULL, del);
19   }
20 }
21 
22 int main() {
23   char *str = "10,20,30";
24   char *arr[3];
25   const char *del = ",";
26   int i = 0;
27   split(arr, str, del);
28  
29   while(i<3)
30     printf("%s\n", *(arr+i++));
31 }
复制代码


執行結果
split

將strtok()稍微加工,將結果塞到array中,就跟JavaScript的split()一模一樣了。

posted on   李sir  阅读(3396)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示