0

I am reading a char array newpath that contains C:\\Program Files\\test software\\app . How to substitute the space to underscore character?

char newPath2[MAX_PATH];
int newCount2 = 0;

for(int i=0; i < strlen(newPath); i++)
 {
 if(newPath[i] == ' ')
    {
     newPath2[i] = '_';         
    }
    newPath2[newCount2]=0;
 }

2 Answers 2

1

newCount2 is always 0, I think you need to increment this counter too. If not Im not sure what you are doing with this statement newPath2[newCount2]=0;

I think you want this:

for(int i=0; i < strlen(newPath); i++)
 {
 if(newPath[i] == ' ')
    {
     newPath2[i] = '_';         
    }else{
     newPath2[i]=newPath[i];
    }
 }
Sign up to request clarification or add additional context in comments.

Comments

1

Don't use strlen in for, is uses O(n) time - loops through the entire string each time it's called - so will make your for run very slowly as it gets called each step in the for.

Better:

char newPath2[MAX_PATH];
int newCount2 = 0;
const int length = strlen(newPath);

for(int i=0; i < length; i++)
 {
   if(newPath[i] == ' ')
    {
     newPath2[newCount2++] = '_';         
    } else {
     newPath2[newCount2++] = newPath[i];
    }
 }

This way if you need to replace space with, say, two characters (like \<space>), you could easily replace newPath2[newCount2++] = '_' with: newPath2[newCount2++] = '\\'; newPath2[newCount2++] = ' ';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.