繁体   English   中英

了解C中的字符串数组

[英]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 ,则第一个单词与最后一个单词交换,依此类推。

我假设您了解代码的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”交换,然后将“ 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM