• C

How do I trim a char array?

Hi all ,

How do I trim a char array? .

I have declared a char array for the the size=10 .
A dynamic string , which length will be veried from 0 to 10  is te assigned
with this char array.

If the dynamic string length less than 10 , then i need to trim the extra spaces from
 the char array . How do i do that . I think , its very basic qustion in c , but iam new to
C world .

Help highly apprciated .

Regards,
Yasin.
expertyasinAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

sunnycoderCommented:
>If the dynamic string length less than 10 , then i need to trim the extra spaces from
>the char array . How do i do that .

for a statically defined array, this is not possible ...
e.g. if you have

char a [10];

then there is no way to to make it 11 or 9 ever (unless you change value of 10 and recompile)

what you can do however, is allocate memory dynamically .. this will allow you to change sizes at run time

Moreover, you can allocate only as much as you require ...

char * a;

a = (char *) malloc ( strlen(input) + 1 );
strcpy ( a, input );

if you wish tochange size to say 20, then

a = (char *) realloc ( a, 20 );
0
expertyasinAuthor Commented:

Actually my input string is coming from a function which is out of my scope . In this case , is it possible to identify and remove the extra memory spaces ?.




0
sunnycoderCommented:
if that function declared it as char a[10] , then no there is no way to resize it...

if it used malloc to get the string, then yes it can be trimmed using realloc
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Prepare for an Exciting Career in Cybersecurity

Help prevent cyber-threats and provide solutions to safeguard our global digital economy. Earn your MS in Cybersecurity. WGU’s MSCSIA degree program curriculum features two internationally recognized certifications from the EC-Council at no additional time or cost.

expertyasinAuthor Commented:

 The input string memory is allocated using malloc only .

 Once i get the input string i need to replace its part of the content
 using a  "dynamic" string.

For Ex :

input string : Sky Train
size = 14

i need to replace the   with a number say 160 .
(actually this replacement string size may vary).

then the output string will be :  "Sky160Train"
size=11


--------------------the code as follows -------------------

char *output;
char ch;

output =  (char *)malloc(strlen(input));

for(int k=0;k<strlen(input);k++)
{
     ch=input[k];


     // here the replacement
     if (ch == '&')
     {
                for (glyphptr = glyph;(ch = input[++k]) != EOF && (glyphptr - glyph) < 15;  
                glyphptr ++)
       {
               if (ch == ';' || isspace(ch))   break;
               else *glyphptr = ch;
       }                                                
        if (glyphptr == glyph)
        {
                       ch = '&';
        }
        else
        {                               
           *glyphptr = '\0';      
            ch = iso8859(glyph); //dynamic string generated here
        }
        }

        output[p++] = ch;                          
  }

output= (char *) realloc ( output, p );


-------------------------------------------------------------------------------------

actually it doesnt works . The memory trailing spaces are not removed .

0
sunnycoderCommented:
>The memory trailing spaces are not removed
1. How did you detemine this ?
2. did you initialize p ?
0
expertyasinAuthor Commented:

Yes . I initialized the p value as 0 .
I printed the Input and its size .          They are Sky&nbsp;Train and 14
I printed p value after for loop , before realloc function its 11
After realloc i printed the Output and its size .
They are Sky160Train--- and the size is still  14

Very strange . But i think , i am doing something wrongly .But i cant able to
identify .


0
sunnycoderCommented:
did you place the end of string marker at appropriate place in output ?
strlen() gives you length of string which you are getting as 14 (so your EOS is wrongly placed)
0
marCelloCommented:
Sorry to interupt sunnycoder,
I find that this may help:

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

char* FunctionOutOfScope(char  unedited[]){
    // do whatever
    return (char*) unedited;
}

char* ReplaceChars(char edited[], char toRemove[], char toAdd[]){
    char* final;
    char* aux;
    int A, B, C, D, i, j, k, position;

    A = strlen(toRemove);
    B = strlen(toAdd);
    C = strlen(edited);
    D = strlen(edited) - strlen(toRemove) + strlen(toAdd);

    final = (char*) malloc (D+1);
    aux = (char*) malloc (D+1);

    aux = strstr(edited,toRemove);
    position =(int) (aux - (char*)edited);
    k=0;

    if(aux){
        for(i=0 ; i<position ; i++)
            final[i] = edited[i];
        final[i+1] = '\0';
        strcat(final,toAdd);
        for(j=position+A; j<=C; j++)
            aux[k++] = edited[j];
        aux[j+1] = '\0';
        strcat(final,aux);

        return (char*)final;
    }

    free(final);
    free(aux);
    return NULL;
}

int main(){
    char * s;

    s=(char*) malloc (strlen(FunctionOutOfScope("Sky&nbsp;Train")+1));
    strcpy(s,FunctionOutOfScope("Sky&nbsp;Train"));
    printf("Initial String :%s\n",s);
    printf("Edited String :%s\n",ReplaceChars(s,"&nbsp;","160"));

    free(s);
    return 0;
}
0
marCelloCommented:
i am trying to improve still, so that you can realloc s string to receive the function ReplaceChars. That would do what you are looking for.

Regards
Marcello
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.