C语言写一个函数,从一个字符串中的第p个位置起删除指定长度的字符串,在main中输出最终结果,若输入不合法,则输出 Illegal input,输入一个字符串s、位置p、长度n 输出 删除子串后的字符串
时间: 2024-06-13 18:07:11 浏览: 15
以下是一个C语言函数的例子,用于从一个字符串中的第p个位置起删除指定长度的字符串,并在main函数中输出最终结果:
```c
#include <stdio.h>
#include <string.h>
void deleteSubstring(char *str, int p, int n) {
int len = strlen(str);
if (p < 0 || p >= len || n < 0 || p + n > len) {
printf("Illegal input\n");
return;
}
memmove(str + p, str + p + n, len - p - n + 1);
}
int main() {
char str[100];
int p, n;
printf("输入字符串:");
gets(str);
printf("输入位置p:");
scanf("%d", &p);
printf("输入长度n:");
scanf("%d", &n);
deleteSubstring(str, p, n);
printf("删除子串后的字符串:%s\n", str);
return 0;
}
```
相关问题
用C语言写一个函数,求一个字符串的长度,在main函数中输入字符串,并输出其长度。
以下是用C语言实现求字符串长度的代码:
```c
#include <stdio.h>
int strlen(char *s) {
int len = 0;
while (*s++ != '\0') {
len++;
}
return len;
}
int main() {
char s[100];
printf("请输入一个字符串:");
scanf("%s", s);
int len = strlen(s);
printf("该字符串的长度为:%d\n", len);
return 0;
}
```
该程序中的 `strlen` 函数接收一个指向字符串的指针,通过循环遍历字符串中的每个字符,直到遇到字符串结束符 `\0`,统计字符串的长度并返回。在 `main` 函数中,用户输入一个字符串并调用 `strlen` 函数获取其长度,最后输出结果。
使用c语言写一个函数,求一个字符串的长度。在main函数中输入字符串,并输出其长度。
好的,以下是代码实现:
```c
#include <stdio.h>
int string_length(char str[]) {
int len = 0;
while (str[len] != '\0') {
len++;
}
return len;
}
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
int len = string_length(str);
printf("字符串的长度为:%d\n", len);
return 0;
}
```
代码运行结果:
```
请输入一个字符串:hello world
字符串的长度为:11
```
解释一下代码:
- `string_length` 函数接收一个字符数组 `str`,并通过循环遍历数组中每个元素,直到遇到字符串结尾的标记符 `\0`,统计字符串的长度并返回。
- `main` 函数中先声明一个字符数组 `str`,并通过 `scanf` 函数从控制台读取一个字符串。然后调用 `string_length` 函数计算字符串长度,并输出结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)