[摘]C/C++实现js的split函数功能

今天在网上找了一下,发觉有比较多的方法,现在列出来,需要的朋友可以参考一下。

功能最丰富的就是第一种方法了:

 

1 vector<string> Split(const string& s,const string& match,bool removeEmpty=false,bool fullMatch=false)
2 //参数s为需要肢解的字符串
3 //参数match为肢解匹配字符串
4 //参数removeEmpty为是否删除空字符
5 //参数fullMatch为是否只保留全匹配的字符串
6
7 下面为代码区:
8 #include <string>
9 #include
10
11 namespace Daniweb
12 {
13     using namespace std;
14
15     typedef string::size_type (string::*find_t)(const string& delim,
16                                                 string::size_type offset) const;
17
18     ///
19 /// Splits the string s on the given delimiter(s) and
20 /// returns a list of tokens without the delimiter(s)
21 ///
22 /// The string being split
23 /// The delimiter(s) for splitting
24 /// Removes empty tokens from the list
25 ///
26 /// True if the whole match string is a match, false
27 /// if any character in the match string is a match
28 ///
29 /// A list of tokens
30     vector<string> Split(const string& s,
31                          const string& match,
32                          bool removeEmpty=false,
33                          bool fullMatch=false)
34     {
35         vector<string> result;                 // return container for tokens
36         string::size_type start = 0,           // starting position for searches
37                           skip = 1;            // positions to skip after a match
38         find_t pfind = &string::find_first_of; // search algorithm for matches
39
40         if (fullMatch)
41         {
42             // use the whole match string as a key
43 // instead of individual characters
44 // skip might be 0. see search loop comments
45             skip = match.length();
46             pfind = &string::find;
47         }
48
49         while (start != string::npos)
50         {
51             // get a complete range [start..end)
52             string::size_type end = (s.*pfind)(match, start);
53
54             // null strings always match in string::find, but
55 // a skip of 0 causes infinite loops. pretend that
56 // no tokens were found and extract the whole string
57             if (skip == 0) end = string::npos;
58
59             string token = s.substr(start, end - start);
60
61             if (!(removeEmpty && token.empty()))
62             {
63                 // extract the token and add it to the result list
64                 result.push_back(token);
65             }
66
67             // start the next range
68             if ((start = end) != string::npos) start += skip;
69         }
70
71         return result;
72     }
73 }

 第二种方法:

 

1 #include
2 #include <string>
3 #include
4 using namespace std;
5
6 vector<string> splitEx(const string& src, string separate_character)
7 {
8     vector<string> strs;
9    
10   int separate_characterLen = separate_character.size();//分割字符串的长度,这样就可以支持如“,,”多字符串的分隔符
11     int lastPosition = 0,index = -1;
12     while (-1 != (index = src.find(separate_character,lastPosition)))
13     {
14         strs.push_back(src.substr(lastPosition,index - lastPosition));
15         lastPosition = index + separate_characterLen;
16     }
17     string lastString = src.substr(lastPosition);//截取最后一个分隔符后的内容
18     if (!lastString.empty())
19         strs.push_back(lastString);//如果最后一个分隔符后还有内容就入队
20     return strs;
21 }
22
23 int _tmain(int argc, _TCHAR* argv[])
24 {
25     string s = "123,456,789,0,888";
26     string del = ","
27     vector<string> strs = splitEx(s, del); 
28     for ( unsigned int i = 0; i < strs.size(); i++) 
29     { 
30         cout << strs[i].c_str() << endl;
31     } 
32     return 0
33 }

 

第三种方法:

 

1 #include
2 #include <string>
3 #include
4
5 using namespace std;
6
7 void split(const string& src, const string& separator, vector<string>& dest)
8 {
9     string str = src;
10     string substring;
11     string::size_type start = 0, index;
12
13     do
14     {
15         index = str.find_first_of(separator,start);
16         if (index != string::npos)
17         {   
18             substring = str.substr(start,index-start);
19             dest.push_back(substring);
20             start = str.find_first_not_of(separator,index);
21             if (start == string::npos) return;
22         }
23     }while(index != string::npos);
24     //the last token
25     substring = str.substr(start);
26     dest.push_back(substring);
27 }
28
29
30 int main()
31 {
32     string src = "Accsvr:tcp     -h   127.0.0.1 -p /t 20018   ";
33     vector<string> d, s;
34     vector<string>::iterator p, q;
35     split(src,":",d);
36     for(p=d.begin();p!=d.end();++p)
37     {
38         cout << *p << endl;
39         s.clear();
40         split(*p," /t/n",s);
41         for (q=s.begin();q!=s.end();++q)
42             cout << "/t" << *q << endl;
43     }
44     return 0;
45

 

第四种方法:

 

1 #include
2 #include
3 #include <string.h>
4
5 void split(char *src, const char *separator, char **dest, int *num)
6 {
7     char *pNext;
8     int count = 0;
9     if (src == NULL || strlen(src) == 0) return;
10     if (separator == NULL || strlen(separator) == 0) return;
11     pNext = strtok(src,separator);
12     while(pNext != NULL)
13     {
14         *dest++ = pNext;
15         ++count;
16         pNext = strtok(NULL,separator);
17     }
18     *num = count;
19 }
20
21 int main()
22 {
23     char src[] = "Accsvr:tcp  -h    127.0.0.1      -p/n    20018";
24     char *dest[128];
25     char *dest2[128];
26     int num = 0, num2 = 0;
27     int i, j;
28
29     split(src,":",dest,&num);
30
31     for (i=0;i32     {
33         printf("|%s|/n",dest[i]);
34         split(dest[i]," /t/n",dest2,&num2);
35         for (j=0;j36         {
37             printf("|%s|/n",dest2[j]);
38         }
39     }
40     return 0;
41 }

 

第五种方法:

 

1 #include
2 #include
3 #include <string.h>
4
5 void split(char *src, const char *separator, char **dest, int *num)
6 {
7     char *pSeparator, *pStart, *pEnd;
8     unsigned int sep_len;
9     int count = 0;
10    
11     if (src == NULL || strlen(src) == 0) return;
12    
13     pSeparator = (char *)malloc(16);
14     if (pSeparator == NULL) return;
15    
16     if (separator == NULL || strlen(separator) == 0) strcpy(pSeparator," ");/* one blank by default */
17     else strcpy(pSeparator,separator);
18
19     sep_len = strlen(pSeparator);
20        
21     pStart = src;
22    
23     while(1)
24     {
25         pEnd = strstr(pStart, pSeparator);
26         if (pEnd != NULL)
27         {
28             memset(pEnd,'/0',sep_len);
29             *dest++ = pStart;
30             pEnd = pEnd + sep_len;
31             pStart = pEnd;
32             ++count;
33         }
34         else
35         {
36             *dest = pStart;
37             ++count;
38             break;
39         }
40     }
41     *num = count;
42     if (pSeparator != NULL) free(pSeparator);
43 }
44
45 int main()
46 {
47     char src[] = "Accsvr:tcp  -h    127.0.0.1    -p    20018";
48     char *dest[128];
49     char *dest2[128];
50     int num = 0, num2 = 0;
51     int i, j;
52
53     split(src,":",dest,&num);
54
55     for (i=0;i56     {
57         printf("|%s|/n",dest[i]);
58         split(dest[i],"/t",dest2,&num2);
59         for (j=0;j60         {
61             printf("|%s|/n",dest2[j]);
62         }
63     }
64     return 0;
65 }

 

摘自:http://www.cnblogs.com/jackson-leung/archive/2012/01/28/

转载于:https://www.cnblogs.com/KivenLin/archive/2012/10/04/2711841.html

### 可能导致命令或代码执行漏洞的函数及其原理 #### PHP中的危险函数 PHP 中存在一些容易引发 OS 注入风险的函数,例如 `exec()`、`shell_exec()`、`system()` 和 `passthru()`. 这些函数可以直接调用外部程序并返回其输出结果。如果应用程序允许用户提交的数据未经适当清理就被传送给上述任何一个函数,则可能造成严重的安全隐患[^1]. ```php // 不安全的例子 $cmd = $_GET['command']; $output = shell_exec($cmd); // 用户可以通过URL参数注入恶意指令 echo $output; ``` 为了防范此类攻击,在实际项目里应当避免直接使用来自用户的输入作为这些函数的一部分。 #### Python中的潜在威胁 Python 提供了多种方式来启动子进程以及与其交互的方法, 如 subprocess 模块下的 Popen 函数族 (Popen(), call(), check_call()) 或者 os.system(). 当不当处理时同样会带来同样的问题. ```python import os from subprocess import Popen, PIPE # 危险做法 user_input = input("Enter command:") os.system(user_input) # 直接运行由用户提供的一条或多条Linux/Windows Shell Command ``` 最佳实践中建议采用更严格的替代方案比如 shlex.split 来解析字符串成列表形式再传递给 popen 方法从而降低风险级别;另外也可以考虑完全移除对外部可执行文件调用的需求以彻底消除隐患. #### JavaScript环境里的风险点 Node.js 脚本语言内置 child_process 库提供了 execFile(), spawnSync()/spawnAsync() 等 API 接口用于创建新的进程并与之沟通交流. 如果开发者未能充分考虑到边界情况的话很容易引入类似的缺陷: ```javascript const { exec } = require('child_process'); let userInput = process.argv[2]; exec(`ping ${userInput}`, (err, stdout, stderr)=>{ console.log(stdout); }); ``` 这里假设了一个简单的 ping 测试场景下由于缺乏必要的校验机制所以很可能遭受非法操控进而触发远程代码执行(RCE). #### C/C++编程注意事项 对于C/C++, system() 是最典型的例子之一因为它能够接受一个指向含有要被执行的操作系统级命令串指针做实参; 此外还有诸如 _popen(), execlp() 系列家族成员也具备相似的功能特性因此都需要谨慎对待以免发生意外状况: ```c++ #include <stdlib.h> int main(){ char *cmd="dir"; /* Windows 下 */ //char* cmd ="ls";/* Unix/Linux/MacOS 平台*/ system(cmd); } ``` 以上仅列举了几种常见的高级别的编程环境中易于忽略却十分致命的地方——即当涉及到跨平台移植或是多版本兼容性考量之时往往更容易暴露出隐藏较深的问题所在. ### 防御措施总结 针对前述提到的各种可能性,采取如下策略有助于增强抵御能力: - 对所有不可信源提供的数据实施严格验证; - 尽量选用官方推荐的安全API而非自行拼凑命令行语句; - 使用白名单限定合法选项范围而不是黑名单排除已知坏模式; - 实施最小权限原则只赋予必要资源访问权; - 合理设置超时限制防止长时间挂起影响正常业务流程; - 记录详细的日志便于事后追踪定位异常行为源头.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值