简体   繁体   中英

Space remove from String

#include<stdio.h>
#include<string.h>

int main(){
    char array[]="Arijit Saha Student";
    spaceremover(array);
    getch();
    return 1;
}

int spaceremover(char a[]){
    int i;
   // printf("L=%d",strlen(a));
    char final[strlen(a)+1];
    int count=0;
    for(i=0;i<strlen(a);i++)
    {
        if(a[i]!=' ')
            final[count]=a[i];
        count++;
    }
    final[count]='\0';
    int j=0;
    for(j=0;j<strlen(final);j++)
    printf("%c",final[j]);
    // printf("\n%s",final);
    return 1;
}

With this example code the output is Arijit.Saha , but my desired output is ArijitSahaStudent . Why am I getting the wrong output? Where the . is coming from?

The error is here:

if(a[i]!=' ')
    final[count]=a[i];
count++;

The count++ should be included in the if , so:

if(a[i]!=' ') {
    final[count]=a[i];
    count++;
}

Note: It is considered good programming practice to always use curly braces after if statements.

In the for loop you increase count even if a[i] == ' ' .
So when a[i] == ' ' you only increase count but doesn't set final[count] to anything.

I assume you ment to write:

if (a[i] != ' ')
{
    final[count] = a[i];
    count++;
}

You are not incrementing count correctly. It needs to be in the if loop. This might be easier for you to see if things are indented correctly.

#include<stdio.h>
#include<string.h>

int main(){
  char array[]="Arijit Saha Student";
  spaceremover(array);
  return 1;
}

int spaceremover(char a[]){
  int i;
  // printf("L=%d",strlen(a));
  char final[strlen(a)+1];
  int count=0;
  for(i=0;i<strlen(a);i++)
  {
    if(a[i]!=' ')
      final[count++]=a[i];
  }
  final[count++]='\0';
  int j=0;
  for(j=0;j<strlen(final);j++)
    printf("%c",final[j]);
  // printf("\n%s",final);
  return 1;
}

In the loop, the count should increase if a[i] not equal to space

if(a[i]!=' ') final[count]=a[i]; count++;

if(a[i]!=' ')
final[count++]=a[i];
//count++;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM