2010-12-11 30 views
-2

HI的分裂,我想如何做一個字符串的分裂在C#包括無如何做一個字符串

+2

問題不明確。 – karlphillip 2010-12-11 14:28:29

+1

先做一些研究。 – khachik 2010-12-11 14:29:26

+1

C沒有真正的字符串類型,所以您必須更加明確地說明您想要如何僞造字符串以及如何表示結果。 – 2010-12-11 14:31:03

回答

0
  1. 找到你想分裂的地步
  2. 使兩個緩衝區大到足以容納數據
  3. 的strcpy()或做手工(見例)

在這個代碼中,我假設你有一個字符串str [],並希望它在第一個逗號分割:

for(int count = 0; str[count] != '\0'; count++) { 
    if(str[count] == ',') 
     break; 
} 

if(str[count] == '\0') 
    return 0; 

char *s1 = malloc(count); 
strcpy(s1, (str+count+1));      // get part after 

char *s2 = malloc(strlen(str) - count);   // get part before 
for(int count1 = 0; count1 < count; count1++) 
    s2[count1] = str[count1]; 

明白了嗎? ;)

2

多種方式做到這一點,我只是解釋,而不是爲你寫,因爲這隻能是一個家庭作業(或自我增強的練習,所以意圖是相同的)。

  • 要麼你分割字符串分爲多個字符串,你重新分配到一個多維陣列中,
  • 或者你只是削減分離器中的字符串和添加終端「\ 0」在適當情況下和僅複製每個子字符串的起始地址爲一個指針數組。

在兩種情況下,拆分的方法都是相似的,但在第二種情況下,您不需要分配任何內存(但修改原始字符串),而在第一個中,您爲每個內存創建安全副本子串。

你不是特定的分裂,所以我不知道,如果你想削減子,一個單字節字符,或潛在的分隔符的列表,等...

好運。

0

假設我有函數原型的完全控制,我可以這樣做(讓這一個源文件(沒有的#includes)和編譯,然後與項目的其餘部分鏈接)

如果#include <stddef.h>是的「而不的#include」的東西部分(但它不應該),然後代替size_t,使用unsigned long在下面的代碼

#include <stddef.h> 
/* split of a string in c without #include */ 
/* 
** `predst` destination for the prefix (before the split character) 
** `postdst` destination for the postfix (after the split character) 
** `src` original string to be splitted 
** `ch` the character to split at 
** returns the length of `predst` 
** 
** it is UB if 
**  src does not contain ch 
**  predst or postdst has no space for the result 
*/ 
size_t split(char *predst, char *postdst, const char *src, char ch) { 
    size_t retval = 0; 
    while (*src != ch) { 
     *predst++ = *src++; 
     retval++; 
    } 
    *predst = 0; 
    src++; /* skip over ch */ 
    while ((*postdst++ = *src++) != 0) /* void */; 
    return retval; 
} 

示例用法

char a[10], b[42]; 
size_t n; 
n = split(b, a, "forty two", ' '); 
/* n is 5; b has "forty"; a has "two" */ 
相關問題