HI的分裂,我想如何做一個字符串的分裂在C#包括無如何做一個字符串
Q
如何做一個字符串
-2
A
回答
0
- 找到你想分裂的地步
- 使兩個緩衝區大到足以容納數據
- 的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" */
相關問題
- 1. 如何做一個字符串的urlencoded的字符串替換
- 2. 如何做一個包含一個字符串數組?
- 3. 如何在ahk中的字符串中做一個「`」符號?
- 4. 在字符串[]內做一個循環?
- 5. 如何做到在兩個領域一個上一個字符串一個int
- 6. 如何做一個帶有字符串的布爾if語句?
- 7. Angular2如何做一個URL查詢字符串
- 8. 如何從一個非常長的C++字符串做char * kmers
- 9. 如何用查詢字符串做一個htaccess 301重定向?
- 10. 我如何做一個紅寶石字符串「\(」?
- 11. AS3如何做一個字符串屬性
- 12. 如何抓住一個字符串,它是2個字符串
- 13. 如何在一個字符串中搜索兩個字符串?
- 14. 如何將一個字符串分爲兩個字符串
- 15. 的XPath:如何做一個字符串,字符串,或文本(),另一種功能時搶多串節點
- 16. 如何寫一個做malloc的宏,格式化一個字符串,然後返回格式化的字符串?
- 17. 做一個字符串確定特定字符的存在
- 18. MATLAB - 有沒有辦法做一個字符串中使用多個字符串
- 19. 如何拆分一個字符串並在另一個字符串中找到一個字符串?
- 20. 如何從一個字符串得到一個字符串,開始和一個特定的字符串
- 21. C#:如何獲得一個字符串的第一個字符?
- 22. PHP字符串如何找到一串數字一個數字
- 23. 如何做一個字符串的一個子在這種情況下
- 24. 如何做多行字符串?
- 25. 如何做與redis比較字符串?
- 26. python如何做字符串魔術?
- 27. 如何做XML字符串替換?
- 28. 如何在字符串中「做數學」?
- 29. 如何做字符串Startswith工作
- 30. Go如何做字符串比較?
問題不明確。 – karlphillip 2010-12-11 14:28:29
先做一些研究。 – khachik 2010-12-11 14:29:26
C沒有真正的字符串類型,所以您必須更加明確地說明您想要如何僞造字符串以及如何表示結果。 – 2010-12-11 14:31:03