gpt4 book ai didi

c - 我的实现未能删除 c 中 String 的最后一个字符

转载 作者:行者123 更新时间:2023-11-30 19:30:53 25 4
gpt4 key购买 nike

这是我定义的LinkedList:

typedef struct target{
char my_target[65];
int ID;
struct target *next;
}target_list;

这是一个有效的解决方案:

printf("the last node is %s\n",get_nth(&head,target_id));
if (get_nth(&head,target_id)[strlen(get_nth(&head,target_id))-1] == '\n'){
char *p = get_nth(&head,target_id);
p[strlen(get_nth(&head,target_id))-1] = 0;
//change_nth(&head,target_id);
printf("the copied array is %s\n",p);

}

打印结果如下:

the last node is Git

the copied array is Git

但是我想更改链表中的第n个节点,如下所示:我定义了两个辅助方法,一个用于获取第n个节点,一个用于删除第n个节点的字符数组中的'\n'。

char* get_nth(target_list* head, int index)
{
target_list* current = head;
int cnt = 0;
while(current != NULL){
if (cnt == index)
return(current -> my_target);
cnt++;
current = current -> next;
}
return "";
}

void change_nth(target_list* head, int index)
{
target_list* current = head;
int cnt = 0;
while(current != NULL){
if (cnt == index){
char *p = current -> my_target;
p[strlen(current -> my_target)-1] = 0;
strcpy(current -> my_target,"");
strcpy(current -> my_target,p);

}
cnt++;
current = current -> next;
}
}

这是更改后的主要内容:

printf("the last node is %s\n",get_nth(&head,target_id));
if (get_nth(&head,target_id)[strlen(get_nth(&head,target_id))-1] == '\n'){
//char *p = get_nth(&head,target_id);
//p[strlen(get_nth(&head,target_id))-1] = 0;
change_nth(&head,target_id);
printf("the copied array is %s\n",get_nth(&head,target_id));

}

这里出现错误:

the last node is Git

==25553== Source and destination overlap in strcpy(0x5201470, 0x5201470)
==25553== at 0x4C2E272: strcpy (in *)
==25553== by 0x40120F: change_nth (original.c:213)
==25553== by 0x4015D6: main (original.c:318)
==25553==
the copied array is

C 字符串让我困惑了很长时间,任何帮助将不胜感激!

最佳答案

这里有一些功能

char *removelast(char *str)
{
size_t len;
if(str == NULL) return NULL;
if(!(len = strlen(str))) return str;
str[len - 1] = 0;
return str;
}

char *removenth(char *str, size_t nth) // nth - 0 to strlen - 1
{
size_t len;
if(str == NULL) return NULL;
if(!(len = strlen(str)) || nth >= len) return str;
strcpy(&str[nth], &str[nth + 1]);
return str;
}


int main(void) {
char str[] = "Hello stackoverflow!!";
printf("Original - %s\n", str);
printf("Last removed - %s\n", removelast(str));
printf("Third removed - %s\n", removenth(str,2)); // third means 2
return 0;
}

你可以在这里自己玩一下https://ideone.com/Vnkzjp

您需要了解一些有关指针和指针操作的知识

关于c - 我的实现未能删除 c 中 String 的最后一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49839223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com