First, make sure your code is formatted neatly, with consistent indentation:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <String.h>
int main(){
char string[] ="idan damri is here\n";
char *p = string;
int i = 0;
int j = 1;
int size = strlen(string);
for(; string[i]!= NULL; i++){
if (string[i] == ' ' && string[j]==' '){
string[j] ='\b';
}
j++;
}
printf("%s", string);
return 0;
}
Second, check your compiler warnings:
Code:
/*
||=== scrap_c, Debug ===|
main.c||In function 'main':|
main.c|13|warning: comparison between pointer and integer|
main.c|11|warning: unused variable 'size'|
main.c|7|warning: unused variable 'p'|
||=== Build finished: 0 errors, 3 warnings ===|
*/
The first warning applies to the test case in your "for()" loop. Since you have an array of characters, and not pointers, you shouldn't be checking for NULL. You probably meant to check for the "null character" ('\0'), which is not the same thing.
However, why not just use "size" since this variable already contains the length of the string?
Finally, are you sure this logic is how you want to solve the problem? You're basically inserting backspace characters ('\b') into your array for each sequential space after the first. While this might make the string appear to print with single spaces, your array still contains those extra spaces, in addition to '\b' characters. It would be cleaner to implement logic that shifts the characters in your array, rather than adding backspaces.
However, if you are certain this is how you want to implement the logic, then I suggest you grab a pen and paper and trace through the iterations of the loop to find the problem. I'll offer an illustration to show the issue.
Code:
/*
+---+---+---+---+---+---+---+---+---+---+
| i | s | | | | | h | e | r | e |
+---+---+---+---+---+---+---+---+---+---+
13 14 15 16 17 18 19 20 21 22
> i = 13, j = 14: do nothing
> i = 14, j = 15: do nothing
> i = 15, j = 16: both are spaces, put a '\b' at index 16
+---+---+---+---+---+---+---+---+---+---+
| i | s | | \b| | | h | e | r | e |
+---+---+---+---+---+---+---+---+---+---+
13 14 15 16 17 18 19 20 21 22
> i = 16, j = 17: do nothing
> i = 17, j = 18: both are spaces, put a '\b' at index 18
+---+---+---+---+---+---+---+---+---+---+
| i | s | | \b| | \b| h | e | r | e |
+---+---+---+---+---+---+---+---+---+---+
13 14 15 16 17 18 19 20 21 22
> etc etc...
*/
The backspace at index 16 eliminates the space at index 15.
The backspace at index 18 eliminates the space at index 17.
The result is a loss of all spaces between those words.
Hopefully this will help you track down the cause of your problem and find a solution.