[英]How would I be able to run code for each character in a const char*?
[英]How to remove first character from const char* in C language code
誰能幫幫我嗎? 我需要從 C 中的const char *
中刪除第一個字符。
例如, const char * contents
包含一個'x'
字符作為數組中的第一個字符。 我需要檢測並消除這個字符,在“清理”后修改原始變量。
誰能建議如何實現它? 我對 C 完全陌生(雖然我知道 Java),但似乎無法弄清楚。
Note:
我已經提到了這些,但仍然無法弄清楚: 如何從 C 字符串中刪除第一個字符? - 這告訴如何在輸入為 char * 內容時刪除
和
char* 和 const char* 的區別? 它提到 const char* 是一個可變指針,但指向不可變的字符/字符串
我在下面tried
的方法有效,但為什么有效?(它應該無法修改不可變字符數組內容值“xup”)
#include <stdio.h>
int main()
{
char input[4] = "xup";
removeLeadingX(input);
return 0;
}
int removeLeadingX(const char * contents)
{
//this if condition is something I have to add
//can't modify other code (ex: the method receives const char * only)
if(contents[0] == 'x'){
contents++;
}
printf(contents);//up - why immutable string "xup" updated to "up"?
return 0;
}
您不能從 const char object 中刪除任何內容。
const char *original = "Hello world!";
char *copy = strdup(original);
copy[strlen(copy) - 1] = 0; //removing `!`
const char *original = "Hello world!";
original = strchr(original, 'w');
printf("%s\n", original);
我在下面嘗試的方法有效,但為什么有效?(它應該無法修改不可變的 char 數組內容)
在您的示例中,您修改指針而不是指針引用的 object。 沒關系。
如果您將此 function 聲明為
void removeLeadingX(const char * const contents)
指針也將是const
並且您的代碼將無法編譯。
您是否需要刪除主角,或者干脆忽略它。
這是 function 正在做什么的示例(只需更改指針)
int main() {
char input[4] = "xup";
char *p = input;
printf( "advance\n" );
p = p + 1;
printf( "input: '%s'\n", input );
printf( "p: '%s'\n", p );
printf( "retreat\n" );
p = p - 1;
printf( "input: '%s'\n", input );
printf( "p: '%s'\n", p );
printf( "nothing has been removed or shifted except the pointer 'p'\n" );
return 0;
}
Output:
advance
input: 'xup'
p: 'up'
retreat
input: 'xup'
p: 'xup'
nothing has been removed or shifted except the pointer 'p'
function 聲明int removeLeadingX(const char * contents)
沒有任何意義。 function 應該“就地”修改傳遞的字符串,在這種情況下 function 應該是:
void removeLeadingX (char* contents)
或者 function 應該在某處存儲原始(不可變)字符串的修改副本,在這種情況下 function 可能是:
void removeLeadingX (char* new_str, const char* old_str)
這些可以實現為:
void removeLeadingX (char* contents)
{
if(contents[0]) == 'x')
memmove(&contents[0], &contents[1], 1);
}
或者:
void removeLeadingX (char* new_str, const char* old_str)
{
if(old_str[0] == 'x')
{
// assuming new_str points at a caller-allocated array:
strcpy(new_str, &old_str[1]);
}
}
考慮到main
中的原始 object 不是const
,您可以使用骯臟的技巧修改數組以避免警告:
#include <stdio.h>
#include <string.h>
int removeLeadingX(const char *contents)
{
if (contents[0] == 'x')
{
union {const char *constant; char *not_constant;} dummy = {contents};
memmove(dummy.not_constant, contents + 1, strlen(contents));
}
printf("%s\n", contents);
return 0;
}
int main(void)
{
char input[4] = "xup";
removeLeadingX(input);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.