C语言 从 C 中的字符串/字符数组中删除空格的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13084236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:12:34  来源:igfitidea点击:

Function to remove spaces from string/char array in C

carraysstring

提问by John R

The question asked hereis very similar to what I am having a problem with. The difference is that I must pass an argument to a function that removes the spaces and returns the resulting string/char array. I got the code working to remove the spaces but for some reason I am left with trailing characters left over from the original array. I even tried strncpy but I was having lots of errors.

问的问题在这里是非常相似,我有一个问题。不同之处在于我必须将参数传递给删除空格并返回结果字符串/字符数组的函数。我让代码工作来删除空格,但由于某种原因,我留下了原始数组中遗留的尾随字符。我什至尝试过 strncpy 但我遇到了很多错误。

Here is what I have so far:

这是我到目前为止所拥有的:

#include <stdio.h>
#include <string.h>
#define STRINGMAX 1000                                                      /*Maximium input size is 1000 characters*/

char* deblank(char* input)                                                  /* deblank accepts a char[] argument and returns a char[] */
{
    char *output=input;
    for (int i = 0, j = 0; i<strlen(input); i++,j++)                        /* Evaluate each character in the input */
    {
        if (input[i]!=' ')                                                  /* If the character is not a space */
            output[j]=input[i];                                             /* Copy that character to the output char[] */
        else
            j--;                                                            /* If it is a space then do not increment the output index (j), the next non-space will be entered at the current index */
    }
    return output;                                                          /* Return output char[]. Should have no spaces*/
}
int main(void) {
    char input[STRINGMAX];
    char terminate[] = "END\n";                                             /* Sentinal value to exit program */

    printf("STRING DE-BLANKER\n");
    printf("Please enter a string up to 1000 characters.\n> ");
    fgets(input, STRINGMAX, stdin);                                         /* Read up to 1000 characters from stdin */

    while (strcmp(input, terminate) != 0)                                   /* Check for que to exit! */
    {
        input[strlen(input) - 1] = '
char* deblank(char* input)                                         
{
    int i,j;
    char *output=input;
    for (i = 0, j = 0; i<strlen(input); i++,j++)          
    {
        if (input[i]!=' ')                           
            output[j]=input[i];                     
        else
            j--;                                     
    }
    output[j]=0;
    return output;
}
'; printf("You typed: \"%s\"\n",input); /* Prints the original input */ printf("Your new string is: %s\n", deblank(input)); /* Prints the output from deblank(input) should have no spaces... DE-BLANKED!!! */ printf("Please enter a string up to 1000 characters.\n> "); fgets(input, STRINGMAX, stdin); /* Read up to another 1000 characters from stdin... will continue until 'END' is entered*/ } }

回答by P.P

After removing the white spaces from the inputyou have not terminated it with nul-terminator (\0) because the new length is less than or equal to the original string.

从 中删除空格后,input您还没有使用 nul-terminator ( \0)终止它,因为新长度小于或等于原始字符串。

Just nul-terminate it at the of end your for loop:

只需在 for 循环结束时终止它:

char * deblank(char *str)
{
  char *out = str, *put = str;

  for(; *str != '
char* deblank(char* input)                                                  /* deblank accepts a char[] argument and returns a char[] */
{
    char *output;
    output = malloc(strlen(input)+1);

     int i=0, j=0;
    for (i = 0, j = 0; i<strlen(input); i++,j++)                        /* Evaluate each character in the input */
    {
        if (input[i]!=' ')                                                  /* If the character is not a space */
            output[j]=input[i];                                             /* Copy that character to the output char[] */
        else
            j--;                                                            /* If it is a space then do not increment the output index (j), the next non-space will be entered at the current index */
    }

    output[j] ='
char* deblank(char* input)                                                  
{
char *output=input;
for (int i = 0, j = 0; i<strlen(input); i++,j++)                        
{
    if (input[i]!=' ')                                                  
        output[j]=input[i];                                             
    else`enter code here`
        j--;                                                            
}
output[j]='
char *FilterChars(char *String,char *Filter){
  int a=0,i=0;
  char *Filtered=(char *)malloc(strlen(String)*sizeof(char));
  for(a=0;String[a];a++)
    if(!strchr(Filter,String[a]))
      Filtered[i++]=String[a];
  Filtered[i]=0;
  return Filtered;
}
'; return output; }
'; return output; /* Return output char[]. Should have no spaces*/ }
'; ++str) { if(*str != ' ') *put++ = *str; } *put = '
char str[]={"my name    is Om"};
int c=0,j=0;
while(str[c]!='##代码##'){
    if(str[c]!=' '){
        str[j++]=str[c];
    }
    c++;
}
str[j]='##代码##';
printf("%s",str);
'; return out; }

回答by unwind

You're not terminating the output, and since it might have shrunk, you're leaving the old tail in there.

您没有终止输出,并且由于它可能已经缩小,因此您将旧的尾巴留在那里。

Also, I would suggest that the treatment of j, which is always incremented in the loop and then has to be manually decremented if the current character is not copied, to be somewhat sub-optimal. It's not very clear, and it's doing pointless work (incrementing j) which even has to be undone when it's not desired. Quite confusing.

另外,我建议 的处理j,它总是在循环中递增,如果当前字符没有被复制,则必须手动递减,这在某种程度上是次优的。这不是很清楚,它正在做毫无意义的工作(递增j),甚至在不需要时必须撤消。相当混乱。

It's easier written as:

更容易写成:

##代码##

回答by Whoami

As others mentioned, same string is used for both source and destination, and a end of string is not maintained.

正如其他人提到的,源和目标都使用相同的字符串,并且不维护字符串的结尾。

You could do in the following way also.

您也可以通过以下方式进行。

##代码##

回答by Sankar Mani

You have to return the string after adding the null(\0) terminator after the for loop block

您必须在 for 循环块之后添加 null(\0) 终止符后返回字符串

##代码##

回答by Owl

If you need to filter more than one character at a time, you might find something like:

如果您需要一次过滤多个字符,您可能会发现类似以下内容:

##代码##

Useful; just provide a list of characters in *Filter you wish to strip out. For example "\t\n ", for tabs, newlines and spaces.

有用; 只需在 *Filter 中提供您希望删除的字符列表。例如“\t\n”,用于制表符、换行符和空格。

回答by razAguls deztiny

This code works with time complexity of O(n).

这段代码的时间复杂度为 O(n)。

##代码##