簡體   English   中英

在C中操縱字符串

[英]manipulate strings in C

我必須保存一個字符串中有多少個字母,數字,空格和行:

char string[2048];
...
string = "aaa 111\nsas 23 d\nds";
for(i = 0; i < strlen(string); i++){
    if (isdigit(string[i]) != 0){
        numbers++;
    } else if (isascii(string[i]) != 0){
        letters++;
    } ...
}

它給了我很多錯誤,“從類型'char *'分配給類型'char [2048]'時類型不兼容”和其他錯誤

該代碼有什么問題?

謝謝你,洛倫佐

嘗試,

char string[2048];

strcpy(string,"aaa 111\nsas 23 d\nds");

要么

char string[2048] = "aaa 111\nsas 23 d\nds";

代替

char string[2048];

string = "aaa 111\nsas 23 d\nds";

簡潔版本

您將字符串聲明為char大小為2048的數組:

char string[2048];

這行引起麻煩,因為您分配了char *這是一個指針:

string = "aaa 111\nsas 23 d\nds";

嘗試以下命令,該命令將遍歷char *並復制元素,直到到達字符串的末尾:

strcpy(string, "aaa 111\nsas 23 d\nds");

如果只想給此char []賦予初始值,請使用:

char string[2048] = "aaa 111\nsas 23 d\nds";

長版

在這種情況下,您可以做一些事情,但實際上,使用固定大小的char數組可能很危險。 如果要嘗試復制超過2048個字符的字符串,則將在為該變量分配的空間之后寫入。

您不能僅僅分配它們的原因是它們是char數組,它不是在C中真正定義的操作,char [2048]只是長度為2048*sizeof(char)的一種指針。 strcpy()將迭代第二個參數並復制字符,直到找到0這將標記字符串的結尾)。

您可能需要檢查strncpy()因為如果字符串大於緩沖區,這會更安全。 手冊頁

stpncpy()和strncpy()函數最多將n個字符從s2復制到s1。 如果s2的長度少於n個字符,則s1的其余部分將填充'\\ 0'個字符。 否則,s1不會終止。

char string[2048] = "aaa 111\nsas 23 d\nds";
n = strlen(string);
for(i = 0; i < n; i++){
    if (isdigit(string[i]) != 0){
        numbers++;
    } else if (isascii(string[i]) != 0){
        letters++;
    } ...
}

使用strcpy而不是像string = "aaa 111\\nsas 23 d\\nds"; 或將字符串數組初始化為char string[2048] = "aaa 111\\nsas 23 d\\nds";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM