更改函数,以便用中间大小写替换字符串中的空格"-"



>我得到了这个程序,而不是在有空格的地方打印"-",以更改函数,以便它用"-"永久替换空格:

#include<stdio.h>
void sp_to_dash(const char *s);
int main(){
sp_to_dash("this is a test");//using the function
return 0;
}//end of main
void sp_to_dash(const char *str){//start of the function
while(*str){//start of while
      if(*str==' ')printf("%c",'-');
      else printf("%c",*str);
      str++;
    }//end of while
}//end of function

我实际上确实改变了它,它起作用了,但以一种微弱的方式:

#include<stdio.h>
  void sp_to_dash(char *s);
  int main() {
      char str[] = "this is a test";
      sp_to_dash(str);
      printf("%s", str);
      getchar();
  return 0;
}//end of main
void sp_to_dash(char *str){
while (*str) {
    if (*str == ' ') *str= '-';
    str++;
    }//enf of while
}//end of sp_to_dash

现在我不明白什么,在原始代码(不变的一个)中,我向函数发送了一个即时字符串,但它在第二个代码中接受了它(更改了一个)我必须创建一个新字符串才能接受:

char str[]="this is a test";

为什么我不能做类似的事情:

#include<stdio.h>
 void sp_to_dash(char *s);
  int main() {
    sp_to_dash("this is a string");
  return 0;
 }//end of main
 void sp_to_dash(char *str){
 while (*str) {
     if (*str == ' ') *str= '-';
    str++;
  }//enf of while
}//end of sp_to_dash

这是因为字符串文字被定义为 const char * ,这意味着您不允许修改它的内容。我相信您遇到了一些编译错误,例如"无法将const char *转换为char *"。在这种情况下,最好不要试图通过强制转换为(char *)来欺骗编译器,因为这会导致未定义的行为。

一旦你把你的字符串定义为char str[]="this is a test";,你实际上创建了一个char数组,并相应地初始化它以包含"这是一个测试"的字母(末尾有)。

指向此数组中任何元素的指针的类型char *以便编译成功传递。

最新更新