zoukankan      html  css  js  c++  java
  • (筆記) 如何使用C語言實現split()? (C/C++) (C) (JavaScript)

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

  • 相关阅读:
    Vue $emit()不触发方法的原因
    java 定时任务之一 @Scheduled注解(第一种方法)
    Dubbo的使用及原理浅析.
    Android App 安全的HTTPS 通信
    详解intellij idea搭建SSM框架(spring+maven+mybatis+mysql+junit)
    IDEA 2018集成MyBatis Generator 插件 详解
    自建证书配置HTTPS服务器
    Jsoup(一)Jsoup详解(官方)
    Android使用最小宽度限定符时最小宽度的计算
    可显示行号的log工具
  • 原文地址:https://www.cnblogs.com/lzjsky/p/1861731.html
Copyright © 2011-2022 走看看