[英]Understanding string arrays in c
我正在嘗試理解這一行代碼。
我很難理解為什么需要3個賦值語句。 我認為這是最低限度的要求,我似乎無法完全遵循。
如果有人能用英語指導我完成每一行的工作,那就太好了。
謝謝。
void to_upper(char *word) {
int index = 0;
while (word[index] != '\0') {
word[index] = toupper(word[index]);
index++;
}
}
int length(char *word) {
int index=0;
while (word[index] != '\0')
index++;
return index;
}
void reverse(char *word) {
int index, len;
char temp;
len = length(word);
for (index=0; index<len/2; index++) {
temp = word[index];
word[index] = word[len-1-index];
word[len-1-index] = temp;
}
}
for (index=0; index<len/2; index++) {
1 temp = word[index];
2 word[index] = word[len-1-index];
3 word[len-1-index] = temp;
}
1:存儲word[index]
的值(稍后我們將需要它)
2:將與數組中點等距的單詞數組的值存儲到word[index]
3:將word[index]
的原始值存儲到與數組中點等距的位置
例如:如果index = 0
,則第一個單詞與最后一個單詞交換,依此類推。
我假設您了解代碼的length
和to_upper
部分,因為它們基本上是c ++ 101的東西。
//Well, just be the title, I would assume this function reverses a string, lets continue.
void reverse(char *word) {
int index, len; //declares 2 integer variables
char temp; //creates a temporary char variable
len = length(word); //set the length variable to the length of the word
for (index=0; index<len/2; index++) {
//Loop through the function, starting at
//index 0, going half way through the length of the word
temp = word[index]; //save the character at the index
word[index] = word[len-1-index]; //set the character at the index in the array
//to the reciprocal character.
word[len-1-index] = temp; //Now set the reciprocal character to the saved one.
}
}
//This essentially moves the first letter to the end, the 2nd letter to the 2nd
//to end, etc.
因此,如果您有“種族”一詞,它將“ r”與“ e”交換,然后將“ a”與“ c”交換,以獲得最終的字符串“ ecar”,或向后競賽。
要了解為什么他們需要3個分配:如果設置word[index] = word[len-1-index]
則在兩個地方都存在相同的字符。 這就像將“種族”設置為“種族”一樣。 如果然后設置word[len-1-index] = word[index]
,則只需將相同字符放回第一部分,因此您將從“ racr”轉到“ racr”。 您需要一個臨時變量來保存原始值,以便可以替換字符串開頭的字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.