c - 在 C 中从字符串中删除空格并将其转换为驼峰式大小写格式

标签 c

我有一个尚未编写的程序。它应该从字符串中删除空格,并将其转换为驼峰格式。例如:

输入:世界你好!
应该给出: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/

相关文章:

c - 使用线程的多文件访问

c - 循环数组会导致我的程序崩溃

c# - 类似 translit.net 但在 autohotkey 上

c - 在C中获取指针数组的第一个元素?

c++ - 比较两个字符串看它们是否旋转

当 char 超过时使用 strtoll 将字符串转换为长整型

c - C中动态分配内存的初始化

c - 上采样的正确方法是什么?

c - 如果 getc 读取超过 4096 个字符,则会出错

c - 编译我的 C 程序时发出警告(字符格式,不同类型的 arg)