2013-02-19 44 views
0

我想了解這個特定的代碼行。瞭解字符串數組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; 
    } 
} 
+5

這不僅僅是一行代碼。究竟你對什麼部分感到困惑?假設你問的是「反向」,你將如何用更少的任務來完成它? – jamesdlin 2013-02-19 02:28:07

+1

'to_upper'和'length'並不是你詢問的內容,是嗎? – singpolyma 2013-02-19 02:28:47

+0

爲什麼你有自定義的'length'而不是隻使用'strlen'? – singpolyma 2013-02-19 02:29:06

回答

1

我打算假設你瞭解你的代碼的lengthto_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」,然後「一」與「C」獲得的「ECAR」最後的字符串,或種族向後。

要理解他們爲什麼需要3個作業:如果您設置了word[index] = word[len-1-index]那麼在兩個地方都存在相同的字符。這就像將「種族」設置爲「racr」一樣。如果你設置了word[len-1-index] = word[index],你只需要在第一部分放回相同的角色,所以你會從「racr」到「racr」。您需要一個臨時變量來保存原始值,以便可以替換字符串前面的字符。

+0

它必須是C 101,而不是C++ 101;這是一個C問題! – 2013-02-19 02:40:21

+0

大聲笑,有效。他們甚至在大學裏提供C班嗎?我去的時候沒有。 – ColdLogic 2013-02-19 02:41:54

2
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,第一個單詞與最後一個單詞交換,依此類推。

+0

對不起,我修改了代碼,但沒有問題,問題是關於最後一段。 – user2044189 2013-02-19 02:36:15