将字符串更改为帕斯卡大小写

标签 c

正在处理一些代码。我是 c 的初学者,所以我可能无法理解 super 复杂的语法。正如问题所述,我有一个从用户那里读入的字符串。 “catdog”,程序将其更改为帕斯卡大小写。 “CatDog” 正如您所看到的,每个单词的第一个字母都大写,并且空格被删除。这就是我遇到麻烦的地方,我不知道如何删除空格。我想过放入一个临时数组,但由于范围问题,我无法返回新的字符串数组。提前致谢。另外,我必须留在该功能内,不能创建新的功能。

 #include <stdio.>
 #include <stdlib.h>
 #include <string.h>

char toUpperCase(char ch){ //changes char to uppercase
return ch - 'a'+ 'A';
}

char toLowerCase(char ch){//changes char to lower case
return ch -'A'+'a';
}


void PascalCase(char* word){//"cat dog" "CatDog"
/*Convert to Pascal case
 It is safe to assume that the string is terminated by '\0'*/
char temp[100];//do not know how to implement
int i;
if (word[0] >= 97 && word[0] <= 122) {
    word[0] = toUpperCase(word[0]);
}
    for (i = 1; i < strlen(word); ++i) {
        if (word[i] >= 65 && word[i] <= 90) {
            word[i] = toLowerCase(word[i]);
        }
        if (word[i] == ' '){
            ++i;
            if (word[i] >= 97 && word[i] <= 122) {
                word[i] = toUpperCase(word[i]);
            }
        }
    }

}



int main(){
 char word[100]; 
 printf("Enter phrase:");
 fgets(word, 100, stdin);

 /*Call PascalCase*/
 PascalCase(word);

 /*Print new word*/
 printf("%s\n", word);
 return 0;
}

最佳答案

您可以尝试下面的代码:

  inline char toUpperCase(char c){
    if('a'<=c && c<='z') return c-'a'+'A';
    else return c;
  }
  inline char toLowerCase(char c){
    if('A'<=c && c<='Z') return c-'A'+'a';
    else return c;
  }
  void toPascalCase(char *str){
    int i,j=0; bool first=true;
    for(i=0;str[i];i++){
      if(str[i]==' ') {first=true; continue;}
      if(first) {str[i]=toUpperCase(str[i]); first=false;}
      else str[i]=toLowerCase(str[i]);
      str[j++]=str[i];
    }
    str[j]='\0';
  }

由于删除空格不会增加字符串长度,因此操作可以就地完成。另外,我将大小写检查移至 toUpperCase 函数中,以便使用起来更加方便。使其内联将能够更快地实现。我尝试了不同的输入,例如“猫狗”,或“猫狗”,代码总是给你“CatDog”(帕斯卡情况)。 bool 变量 first 指示当前字符是否是空格后的第一个字符(应大写的单词的开头)。

关于将字符串更改为帕斯卡大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39910062/

相关文章:

C 的 strtok() 和只读字符串文字

c - C11 中是否有定义的方法来进行指针减法?

c - beginPacket 上的 UDP 错误

c++ - 如何使用 C API 而不是实际知道 Clang 的书面 var 类型?

c - 二叉搜索树实现的 Inorder 函数不适用于全局结构指针

c++ - OpenCV:二维数组到 MAT 转换后 MAT 中的垃圾值

c++ - 使用 Visual Studio C++ 编译器编译 C 代码是否有任何(与性能相关的)缺点?

c - 使用20个线程写入文件

c - C语言中如何清除缓冲区?

c - 在 C 中写入超出数组末尾的内容