我有一个尚未编写的程序。它应该从字符串中删除空格,并将其转换为驼峰格式。例如:
输入:世界你好!
应该给出:helloWorld!
现在我对这个程序有几个问题。
#include <stdio.h>
#include <ctype.h>
char *convert(char *f) {
char *save = f;
char *output = f;
int in_a_word = 1;
while(isspace(*f)) f++;
for(; *f; f++) {
if(isspace(*f)) in_a_word = 0;
else
{
if(in_a_word) {
*output= tolower(*f);
}
else {
*output = toupper(*f);
}
in_a_word = 1;
output++;
}
*output= '\0';
}
return save;
}
int main(void) {
char str[] = " Hello World\t";
printf("Modified: -->%s<---\n", convert(str));
getchar();
}
我的问题:
char *save = f;
char *output = f;
如果我理解正确的话,它们都应该指向f。我写了一个实验程序:
int main(void) {
char *s = " Hello";
char *ment = s;
printf("Original:\n-->%s, %p<---\n-->%s, %p<---\n\n", s,s,ment,ment);
while(isspace(*s)) s++;
printf("Modified:\n-->%s, %p<---\n-->%s, %p<---", s,s,ment,ment);
getchar();
}
在这个程序中,我将 s 的地址保存在 ment 中。当我使用第一个printf时,它表明它们完全相等,并且它们指向相同的位置。我对s做了一点修改。这会删除 s 中的所有空格,但 ment 保持不变。甚至他们的位置也发生了变化。
回到原来的程序。在convert函数中,我们返回save,但它没有被修改。所以我的问题是:谁能解释一下为什么我们要返回保存?和/或我应该引用哪些源 Material 。我读了几本关于指针的书,但没有提到这一点。
最佳答案
In the convert function we are returning save, but it has not been modified. So my question is: can anyone explain why we are returning save?
save
是保存字符串原来的位置。请注意,output
指针在函数内被修改:
output++; // output pointer has been modified to point to next character
所以你不能返回output
本身 - 你想返回字符串的原始位置。
换句话说,该函数中的两个指针有不同的用途:
output
是修改字符串内容(this指针在整个函数中不断变化)save
用于存储原始字符串位置(该指针在函数内不会更改)并将其返回给调用函数
关于c - 在 C 中从字符串中删除空格并将其转换为驼峰式大小写格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41884951/