• 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 .

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

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.

>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 );
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 ?.

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

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
Identify and Prevent Potential Cyber-threats

Become the white hat who helps safeguard our interconnected world. Transform your career future by earning your MS in Cybersecurity. WGU’s MSCSIA degree program was designed in collaboration with national intelligence organizations and IT industry leaders.

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"

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

char *output;
char ch;

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

for(int k=0;k<strlen(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 = '&';
           *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 .

>The memory trailing spaces are not removed
1. How did you detemine this ?
2. did you initialize p ?
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 .

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)
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);

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

        return (char*)final;

    return NULL;

int main(){
    char * s;

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

    return 0;
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.

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

From novice to tech pro — start learning today.