我有字串,以陣列形式提供。然后我做這個操作,比如重新排列單詞中的字母。應該是“我喜歡狗”->“我 keli gsdo” 然后我需要做相反的事情,比如把這個字串變成“我再次喜歡狗”
這就是我得到句子的方式:
do {
gets_s(sent);
if (strcmp(sent, STEND) == 0)
break;
mp[k] = _strdup(sent);
} while ( k < NMAX);
以及我如何改變字母
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");
}
但是當我想在陣列 mp 中再次得到我的第一句話時,我得到了“likeldogsdo”。由于沒有空格,我無法再次獲取此文本。我如何在這個字串中加入空格?
uj5u.com熱心網友回復:
了解strtok實際作業原理很重要。
在 C 中,每個字串都以 NUL 字符 ( "\0") 結尾,以標記字串的結尾。"Foo"事實上也是如此
{ 'F', 'o', 'o', '\0' }
在記憶中。現在要做的strtok是搜索令牌并將令牌替換為 NUL 位元組。所以如果你叫這個
char str[] = "I like dogs";
strtok(str, " ");
字串str更改為
"I\0like dogs"
并回傳指向開頭的指標。如果您現在閱讀該字串,則它只是"I". 下次呼叫strtok字串時將如下所示:
"I\0like\0dogs"
并且您會得到一個指向 的指標l,因此將其作為字串讀取會得到您"like"。第三次呼叫將只回傳一個指向 的指標d,因為沒有更多空格,因此您得到"dogs"。
請注意如何strtok更改您的初始字串,因為它用 NUL 位元組替換了空格,以及您如何永遠不會從strtok呼叫中取回空格?
我想現在你明白為什么你的代碼沒有按照你期望的方式作業,不是嗎?
一個更簡單的方法是根本不使用strtok。畢竟在 C 字串中查找空格字符非常簡單:
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.
在另一個回圈中重復此回圈,無需重置nextSep為零,您將從一個空間跳到另一個空間,直到到達字串的末尾。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/374135.html
上一篇:計算字串觀察中單詞串列的出現次數
