使用c语言编写程序 使用自定义函数 求一个字符串的长度
时间: 2023-12-14 08:38:53 浏览: 29
可以使用自定义函数 `strlen` 来求一个字符串的长度,函数的实现如下:
```c
#include <stdio.h>
int strlen(char str[]) {
int len = 0;
while (str[len] != '\0') {
len++;
}
return len;
}
int main() {
char str[] = "hello world";
int len = strlen(str);
printf("The length of the string is %d\n", len);
return 0;
}
```
在 `strlen` 函数中,我们使用了一个 `while` 循环来遍历整个字符串,直到遇到字符串的结尾符 `\0`,才停止循环。循环中,每次将计数器 `len` 加 1,最后返回计数器的值作为字符串的长度。
在 `main` 函数中,我们定义了一个字符串 `str`,并调用 `strlen` 函数来获取该字符串的长度,并打印输出结果。
注意,在 C 语言中,字符串的结尾必须包含一个特殊的字符 `\0`,表示字符串的结束。因此,在遍历字符串时,需要检查字符串是否已经结束,才能正确计算字符串的长度。
相关问题
使用c语言编写程序 使用自定义函数 完成两个字符串的连接
下面是使用 C 语言编写程序,使用自定义函数完成两个字符串的连接的示例代码:
```c
#include <stdio.h>
#include <string.h>
void str_concat(char *dest, const char *src)
{
// 获取 dest 的长度
int dest_len = strlen(dest);
// 将 src 拼接到 dest 后面
int i;
for (i = 0; src[i] != '\0'; i++) {
dest[dest_len + i] = src[i];
}
// 添加字符串结束标志
dest[dest_len + i] = '\0';
}
int main()
{
// 定义两个字符串
char str1[100] = "hello";
char str2[100] = "world";
printf("Before concatenation: %s %s\n", str1, str2);
// 调用自定义函数进行字符串拼接
str_concat(str1, str2);
printf("After concatenation: %s\n", str1);
return 0;
}
```
在上面的程序中,我们定义了一个自定义函数 `str_concat()`,该函数接受两个参数:`dest` 和 `src`,其中 `dest` 是目标字符串,`src` 是要拼接的字符串。在函数中,我们先获取 `dest` 的长度,然后将 `src` 拼接到 `dest` 的末尾,最后添加字符串结束标志。在 `main()` 函数中,我们调用了 `str_concat()` 函数对两个字符串进行拼接,并输出结果。
用c语言编写自定义函数完成两个字符串的连接功能,要求自定义函数形参采用指针。
好的,以下是一份用 C 语言编写自定义函数实现字符串连接的代码示例:
```c
#include <stdio.h>
#include <string.h>
void str_cat(char *str1, char *str2)
{
int len1 = strlen(str1);
int len2 = strlen(str2);
int i, j;
for (i = len1, j = 0; j < len2; i++, j++) {
str1[i] = str2[j];
}
str1[i] = '\0';
}
int main()
{
char str1[100] = "Hello, ";
char str2[] = "world!";
str_cat(str1, str2);
printf("%s\n", str1);
return 0;
}
```
在这个代码中,我们定义了一个自定义函数 `str_cat`,该函数接收两个字符串指针作为参数。函数内部首先计算两个字符串的长度,然后使用一个循环将第二个字符串中的字符逐一拷贝到第一个字符串的末尾,并在最后加上一个 NULL 字符来表示字符串的结束。
在 `main` 函数中,我们声明两个字符串变量 `str1` 和 `str2`,并初始化 `str1` 为 `"Hello, "`,`str2` 为 `"world!"`。然后我们调用 `str_cat` 函数将 `str2` 连接到 `str1` 的末尾,最后输出连接后的结果。