[英]Trying to delete string characters
我試圖通過用空引號將它們替換來刪除字符串中的字符。 它給我以下錯誤消息:
incompatible pointer to integer conversion assigning to
'char' from 'char [1]' [-Wint-conversion]
source[i] = "";
^ ~~
當我用字符替換空字符串時遇到相同的錯誤,我以為這是替換數組元素的過程,所以我不確定如何繼續。
這是我的代碼:
#include <stdio.h>
#include <string.h>
int removeString(char source[], int startIndex, int numberRemove) {
int i;
for (i = startIndex; i < startIndex + numberRemove; i++) {
printf ("%c", source[i]);
source[i] = "";
}
for (i = 0; i < strlen(source); i++) {
printf("%c\n", source[i]);
}
return 0;
}
int main (void) {
char text[] = { 'T', 'h', 'e', ' ', 'w', 'r', 'o', 'n', 'g', ' ', 's', 'o', 'n' };
removeString(text, 4, 6);
return 0;
}
嘗試使用:
memset(source, 0, strlen(source));
這會將整個字符串長度設置為null終止字符。 您在上面所做的事情:
source[i] = "";
出現錯誤是出於以下幾個原因:
您不能將“”分配給字符! “”是一個字符*(最好說一個ASCII0字符串)。
我認為您想在字符串中插入0碼! 這不是一個好選擇,因為0表示ASCII0字符串的結尾。
您可以將char替換為空格:
source[i] = ' ';
但我認為這不是您想要的!
要從字符串中刪除字符,必須將所有要刪除的字符移到要刪除的字符之后。 ;)
如果您希望將ASCII0字符串打印並作為空字符串進行管理
只需在第一個字節中輸入0!
source[0]=0;
要么
*source=0;
解決了。 基本上,我遍歷字符串並打印出char,如果它們在指定的值范圍內。
#include <stdio.h>
#include <string.h>
int removeString(char source[], int startIndex, int numberRemove) {
int i;
for (i = 0; i < strlen(source); i++) {
if (i < startIndex || i >= startIndex + numberRemove) {
printf("%c", source[i]);
}
}
return 0;
}
int main (void) {
char text[] = { 'T', 'h', 'e', ' ', 'w', 'r', 'o', 'n', 'g', ' ', 's', 'o', 'n', '\0' };
removeString(text, 4, 6);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.