c语言去掉字符串后的\r\n
时间: 2024-01-05 14:02:16 浏览: 628
以下是C语言去掉字符串后的\r\n的代码实现:
#include <stdio.h>
#include <string.h>
char *trim(char *str)
{
char *p = str;
int len = strlen(p);
while (isspace(p[len - 1])) p[--len] = 0;
while (*p && isspace(*p)) ++p, --len;
memmove(str, p, len + 1);
return str;
}
int main()
{
char str[] = "hello world\r\n";
printf("Before trim: %s", str);
trim(str);
printf("After trim: %s", str);
return 0;
}
运行结果为:
Before trim: hello world
After trim: hello world
相关问题
利用C语言依次取出字符串中所有数字字符,形成新的字符串,并取代原字符串。(例如:原字符串为he2llo 3wo5rld9,去除数字后新字符串为hello wolrd)
在C语言中,我们可以利用指针和循环来实现这个功能。这里可以采用isdigit()
函数从C标准库ctype.h
中获取帮助,它用于检查字符是否是十进制数字。下面是一个简单的示例程序:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void remove_digits(char *str) {
int i = 0;
char new_str[strlen(str)]; // 新字符串长度等于原字符串
for (int j = 0; str[j]; ++j) { // 遍历原字符串
if (!isdigit(str[j])) { // 如果不是数字字符
new_str[i++] = str[j]; // 将非数字字符复制到新字符串
}
}
new_str[i] = '\0'; // 结束字符串
// 替换原字符串
strcpy(str, new_str);
}
int main() {
char input[] = "he2llo 3wo5rld9";
printf("Original string: %s\n", input);
remove_digits(input);
printf("New string without digits: %s\n", input);
return 0;
}
运行上述代码,将得到如预期的结果:"Original string: he2llo 3wo5rld9" -> "New string without digits: hello wolrd".
C语言如何去掉字符串中的换行符和回车符
在 C 语言中,可以使用字符串处理函数 strcspn
、strchr
和 strcpy
来去掉字符串中的换行符和回车符。
具体步骤如下:
使用
strcspn
函数找到字符串中第一个换行符或回车符的位置,它返回的是第一个匹配字符的位置。如果找到了换行符或回车符,则使用
strcpy
函数将该位置之后的字符全部复制到该位置,覆盖换行符或回车符。继续使用
strcspn
函数寻找下一个换行符或回车符的位置,直到字符串结束。
示例代码如下:
#include <stdio.h>
#include <string.h>
void remove_newline(char str[]) {
char *pos;
while ((pos = strchr(str, '\n')) != NULL || (pos = strchr(str, '\r')) != NULL) {
strcpy(pos, pos+1);
}
}
int main() {
char str[100] = "Hello, world!\nThis is a test.\r\n";
printf("Before: %s", str);
remove_newline(str);
printf("After: %s", str);
return 0;
}
输出结果为:
Before: Hello, world!
This is a test.
After: Hello, world!This is a test.
相关推荐













