阅读量:117
在C语言中,可以使用一些内置函数和自定义函数来实现字符串的变换
- 将字符串转换为大写:
#include
#include
#include
void to_upper(char *str) {
for (int i = 0; str[i]; i++) {
str[i] = toupper(str[i]);
}
}
int main() {
char str[] = "hello world";
to_upper(str);
printf("%s\n", str);
return 0;
}
- 将字符串转换为小写:
#include
#include
#include
void to_lower(char *str) {
for (int i = 0; str[i]; i++) {
str[i] = tolower(str[i]);
}
}
int main() {
char str[] = "HELLO WORLD";
to_lower(str);
printf("%s\n", str);
return 0;
}
- 反转字符串:
#include
#include
void reverse_string(char *str) {
int len = strlen(str);
for (int i = 0, j = len - 1; i < j class="hljs-type">char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
int main() {
char str[] = "hello world";
reverse_string(str);
printf("%s\n", str);
return 0;
}
- 删除字符串中的空格:
#include
#include
void remove_spaces(char *str) {
int i, j = 0;
int len = strlen(str);
for (i = 0; i < len class="hljs-keyword">if (str[i] != ' ') {
str[j++] = str[i];
}
}
str[j] = '\0';
}
int main() {
char str[] = "hello world";
remove_spaces(str);
printf("%s\n", str);
return 0;
}
这些示例展示了如何使用C语言实现字符串的基本变换。你可以根据需要修改这些代码以满足特定的需求。