(筆記) 如何使用C語言實現Split()? (C/C++) (C) (JavaScript)

http://www.cnblogs.com/lzjsky/archive/2010/10/26/1861731.html
http://www.cnblogs.com/lzjsky/archive/2010/10/26/1861731.html
http://www.cnblogs.com/lzjsky/archive/2010/10/26/1861731.html
http://www.cnblogs.com/lzjsky/archive/2010/10/26/1861731.html

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   * =  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()一模一樣了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值