如何只保留一个字符串的前六位
时间: 2024-02-13 14:04:38 浏览: 14
可以使用C语言中的字符串截取函数`strncpy()`或者`memcpy()`来截取字符串的前六位。以下是两种方法的示例代码:
方法一:使用`strncpy()`
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[100], new_str[7];
int i;
printf("Enter a string: ");
gets(str);
strncpy(new_str, str, 6); // 从str中截取前6个字符到new_str中
new_str[6] = '\0'; // 添加字符串结束符
printf("Resultant string: %s", new_str);
return 0;
}
```
方法二:使用`memcpy()`
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[100], new_str[7];
int i;
printf("Enter a string: ");
gets(str);
memcpy(new_str, str, 6); // 从str中复制前6个字符到new_str中
new_str[6] = '\0'; // 添加字符串结束符
printf("Resultant string: %s", new_str);
return 0;
}
```
两种方法的输出结果都是截取后的前六个字符。其中,`strncpy()`函数会自动在截取的字符串末尾添加字符串结束符,而`memcpy()`函数则需要手动添加。