I have strings, that served in array. Then I do this manipulation, like rearranging letters in word. It should be like "I like dogs" -> "I keli gsdo" And then i need to do the opposite, like make this string to "I like dogs again"
It's how I get sentences:
do {
gets_s(sent);
if (strcmp(sent, STEND) == 0)
break;
mp[k] = _strdup(sent);
} while ( k < NMAX);
And how i changing letters
for (int rech = 0; rech < k; rech ) {
char *piece;
piece = strtok(mp[rech], " ");
while (piece != NULL) {
char temp[20];
char *piece2 = temp;
strcpy(piece2, piece);
int k = strlen(piece) / 2;
int i =strlen(piece);
for (i - 1; i != 0; i--) {
piece[k - 1] = piece2[i - 1];
k--;
}
k = strlen(piece) / 2;
for (i = 0;k!=strlen(piece);i ) {
piece[k] = piece2[i];
k ;
}
//printf("%s ", piece1);
printf("%s ", piece);
piece = strtok(NULL, " ");
}
printf("\n");
}
But when I want to get my first sentence again in array mp, i've got "likeldogsdo". And as there is no spaces, I can't get this text again. How I can put spaces into this string?
CodePudding user response:
It's important to understand how strtok
actually works.
In C, every string is terminated by a NUL character ("\0"
), to mark the end of the string. So "Foo"
is in fact
{ 'F', 'o', 'o', '\0' }
in memory. Now what strtok
does is searching for a token and replacing the token by a NUL byte. So if you call this
char str[] = "I like dogs";
strtok(str, " ");
the string str
is changed to
"I\0like dogs"
and a pointer to the beginning is returned. If you now read that string, it's just "I"
. Next time you call strtok
the string will look like this:
"I\0like\0dogs"
and you get a pointer to the l
, so reading this as a string gets you "like"
. The third call will just return a pointer to the d
, as there are no further spaces and thus you get "dogs"
.
Note how strtok
changes your initial string, as it replaces the spaces with NUL bytes, and how you never get the spaces themselves back from your strtok
calls?
I think by now you understand why your code is not working the way you expect it to work, don't you?
A much easier approach would be to not use strtok
at all. After all finding a space character in a C string is pretty simple:
char * str = ...;
size_t nextSep = 0;
while (str[nextSep] && str[nextSep] != ' ') nextSep ;
// When you get here, str[nextSep] is either a space
// or a NUL byte, in which case the end of the string was
// reached before a space was found.
Repeat this loop within another loop and without resetting nextSep
back to zero and you will jump from space to space until you hit the end of the string.