gpt4 book ai didi

c - 为什么我的removeString函数没有删除字符?

转载 作者:行者123 更新时间:2023-12-02 09:24:58 26 4
gpt4 key购买 nike

我正在完成一本书中的练习,除了 printfscanf 之外,我不允许使用任何库函数。

我编写了一个接受字符串的程序。然后,您可以输入要从字符串中删除的字符数。然后选择在哪个索引处执行此操作。

我的尝试是循环遍历我想要保留在函数末尾的字符,然后用我想要丢失的函数替换它们。

出于某种原因,它的行为恰恰相反。

如果我输入字符串:“错误的儿子”然后选择删除 6 个字符并从数组的第 4 个索引开始,

我应该得到:“儿子”

相反,我得到了“the wro”

我已经为此苦苦挣扎了 4 个小时。

你能告诉我哪里出错了吗?

#include <stdio.h>

void removeString(char source[], int start, int count);
int stringLength(const char string[]);

int main(void)
{
int start, count;
char source[20];

printf("What's your string?\n");
scanf("%[^\n]s", source);

printf("How many characters do you want to remove?\n");
scanf("%i", &count);

// Choose which index to start deletion from
printf("Where are we starting from?\n");
scanf("%i", &start);

// Call function to remove characters from string
removeString(source, start, count);

// print out result, stored in source
printf("Here's the result: %s\n", source);

return 0;
}

void removeString(char source[], int start, int count)
{
int i, j;

// Find length of string
int length = stringLength(source);


//loop through the last few characters that we DO want to keep until we hit the end of the string
for(i = (start+count); i <= length; i++)
{
//loop backwards through the string, from the first of the ones we want to keep, stop at the 'start' of the index
for(j = (start+count)-1; j <= start; j--)
{
// assign 'i' which is the last few characters we want to keep and put them in the place of the characters we want to delete
source[j] = source[i];
}
}

// assign a null character to end the string once we've finished modifying
source[count + 1] = '\0';
}

int stringLength(const char string[])
{
int count =0;

while(string[count] != '\0')
count++;

return count;
}

最佳答案

您只需要一个 for 循环即可实现这一点。假设我们可以成功避免超出字符串末尾,您可以编写如下内容:

for(i = start; i < start + count && i < length; i++) {
source[i] = source[i+count];
}

那么你只需要在正确的位置设置一个空字符即可。但是,这不算数。也许是 length-count-1 (或考虑 start+count),因为您要删除“count”个字符。

关于c - 为什么我的removeString函数没有删除字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38574646/

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