[英]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.