从C中的字符串中删除字符 [英] Remove character from string in C

查看:99
本文介绍了从C中的字符串中删除字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个函数,该函数从字符串中删除某些选择的字符.在我的情况下,我试图合并"空格,这意味着如果字符串中有多个相应的空格,则会保留一个空格.
例如:在我的函数中输入的字符串"Hello World"(Hello World之前和之后的多个空格,由于某些原因未在此处显示)输入到我的函数中将变为"Hello World".该函数返回删除的字符数.

我写的函数是这样的:

Hi, I am trying to code a function that removes certain characters of choice from a string. In my case I am trying to "merge" whitespaces, meaning that if there are multiple consequent whitespaces in a string, one will be left.
For example: The string " Hello World " (multiple consequent spaces before Hello and after World, for some reason not seen here), entered into my function will become " Hello World ". The function returns the number of characters removed.

The function that I wrote is this:

int handle_text(char *st)
{
    int size = strlen(st);
    int space = 0;
    char* newst = st;
    for (int i = 0, j=0; i < size; i++ )
    {
        if (st[i] != ' ')
        {
            newst[j] = st[i];
            space = 0;
            j++;
        }
        else if (!space)
        {
            newst[j]=' ';
            space = 1;
            j++;
        }
        
    }
    newst[j]='\0';
    return (size-strlen(newst));
}



问题在于该函数无法写入或更改原始字符串.在这一行中:newst [j] ='''';程序崩溃. (最新点与st相同).
我还尝试将newst作为不同的指针开始,最后使st指向newst指向的位置,但是在函数外部看不到效果.

PS:总体复杂度应为O(n);



The problem is that the function cannot write or change the original string. In the line: newst[j]='' ''; the program crashes. (newst points to the same as st).
I also tried starting newst as a different pointer, and in the end making st point to where newst is pointing, but the effect is not seen outside the function.

PS: Overall complexity should be O(n);

推荐答案

我假设您的程序因访问冲突写入位置..."而崩溃.
这是因为handle_text函数使用无法更改的字符串调用的原因. 调用
I am assuming your program crashes with an "Access violation writing location...".

This is caused because the handle_text function is called with a string that cannot be changed.
Calling the function like
handle_text( "  Hello World  " );

char* st = "  Hello World  ";

handle_text( st );

将导致访问冲突.这是因为这些字符串文字存储在只读存储器中,任何尝试更改它们的尝试都将导致访问冲突.

但是像

will cause the access violation. This is because these string literals are stored in read only memory and any attempt trying to alter them will result in the access violation.

However calling it like

char st[] = "  Hello World  ";

handle_text( st );

将起作用.


最简单的解决方案是:从要删除的字符开始(我们将其称为位置i),用i + 1处的字符重写它,并对其后的每个字符重复此操作.不要忘记跳过最后一项,因为后面没有任何内容!

数组是一个设置的大小,您不能简单地从中删除"某项,因为这会减小大小,因此您可以通过重写要删除的值中的每个值到下一个项目的末尾来完成此操作. .
The simplest solution is this: start at the character you want to remove (let''s call it position i), rewrite it with the character at i + 1, and repeat for every character after it. Don''t forget to skip the last item, because there is nothing after it!

An array is a set size, you can''t simply "remove" something from it, because that would decrease the size, so instead you accomplish this by rewriting every value from the one you want to remove to the end with the next item.


您的解决方案有很多问题.这是一个很好的:
Your solution is very buggy. Here is a good one:
int handle_text(char* st)
{
	int space = 0;
	char* newst = st;
	for (; st[0]; ++st)
	{
		if (st[0] != ' ')
		{
			newst[0] = st[0];
			++newst;
			space = 0;
		}
		else if (!space)
		{
			newst[0] = st[0];
			++newst;
			space = 1;
		}
	}
	newst[0] = 0;
	return (int)(st - newst);
}

int main()
{
	char TXT[] = "Less  space  is  better.";
	int removed = handle_text(TXT);
	printf("%d %s\n", removed, TXT);
	return 0;
}


请注意,不需要调用strlen(),因为您始终必须从头到尾遍历原始字符串,而无需知道完整长度.另一件事使您的代码变慢并且有错误,这是您在代码的每次迭代中始终在字符串末尾写一个零.仅当迭代完成时,它足以零终止目标字符串.请注意,在我的解决方案中,迭代之后,源指针指向源字符串的零终止符,而最新指针指向目标字符串的零终止符.减去它们会得到长度上的差异.


Note that calling strlen() isn''t needed because you always have to walk through the original string from beginning to end without the need to know the full length. Another thing that makes you code slow and also buggy is that you always write a zero to the end of the string in every iteration in your code. Its enough to zero terminate the destination string only when the iteration is finished. Note that in my solution after the iteration the source pointer points to the zero terminator of the source string hile the newst pointer points to the zero terminator of the dest string. Subtracting them gives the difference in their length.


这篇关于从C中的字符串中删除字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆