了解字符串数组c
我想了解这个特定的代码行。了解字符串数组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;
}
}
我打算假设你了解你的代码的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”,然后“一”与“C”获得的“ECAR”最后的字符串,或种族向后。
要理解他们为什么需要3个作业:如果您设置了word[index] = word[len-1-index]
那么在两个地方都存在相同的字符。这就像将“种族”设置为“racr”一样。如果你设置了word[len-1-index] = word[index]
,你只需要在第一部分放回相同的角色,所以你会从“racr”到“racr”。您需要一个临时变量来保存原始值,以便可以替换字符串前面的字符。
它必须是C 101,而不是C++ 101;这是一个C问题! – 2013-02-19 02:40:21
大声笑,有效。他们甚至在大学里提供C班吗?我去的时候没有。 – ColdLogic 2013-02-19 02:41:54
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
,第一个单词与最后一个单词交换,依此类推。
对不起,我修改了代码,但没有问题,问题是关于最后一段。 – user2044189 2013-02-19 02:36:15
这不仅仅是一行代码。究竟你对什么部分感到困惑?假设你问的是“反向”,你将如何用更少的任务来完成它? – jamesdlin 2013-02-19 02:28:07
'to_upper'和'length'并不是你询问的内容,是吗? – singpolyma 2013-02-19 02:28:47
为什么你有自定义的'length'而不是只使用'strlen'? – singpolyma 2013-02-19 02:29:06