2016-06-09 57 views
0

我想將一個字符串拆分爲一個字符串數組,我需要在遇到一個','時拆分它們。C++等價的.split()

在Java中,我們可以使用: -

String[] splitArray = input.split(","); 

是否有任何C這樣的功能++或者我會堅持這樣做使用循環的傳統方法是什麼?

提供的解決方案類似Ques。在StackOverflow不適用於除空間以外的任何分隔符。

回答

-2

的strtok()你想要做什麼:http://www.cplusplus.com/reference/cstring/strtok/

從例如:

/* strtok example */ 
#include <stdio.h> 
#include <string.h> 

int main() 
{ 
    char str[] ="- This, a sample string."; 
    char * pch; 
    printf ("Splitting string \"%s\" into tokens:\n",str); 
    pch = strtok (str," ,.-"); 
    while (pch != NULL) 
    { 
     printf ("%s\n",pch); 
     pch = strtok (NULL, " ,.-"); 
    } 

return 0; 

}

+1

這支持C prgramming,但對我來說,我使用 的#include ,而不是#include /#包括並且需要String作爲 string name =「我的名字」; 上述功能在這裏不起作用。 –

+0

你所做的一切就是爲C++問題提供剽竊的C答案。恕我直言,這不是一個好的答案。 – NathanOliver

+0

它工作正常?當你說這個功能不起作用時,你的問題到底是什麼?這是完全有效的C++代碼,在這裏工作得很好。 – Lee