C++用指针变量编写下列处理函数:字符串拼接函数 ,字符串比较函数, 取字符串长度函数
时间: 2024-05-13 14:20:44 浏览: 14
1. 字符串拼接函数:
```c
void string_concat(char *str1, char *str2) {
while (*str1 != '\0') {
str1++;
}
while (*str2 != '\0') {
*str1 = *str2;
str1++;
str2++;
}
*str1 = '\0';
}
```
2. 字符串比较函数:
```c
int string_compare(char *str1, char *str2) {
while (*str1 == *str2) {
if (*str1 == '\0') {
return 0;
}
str1++;
str2++;
}
return (*str1 - *str2);
}
```
3. 取字符串长度函数:
```c
int string_length(char *str) {
int length = 0;
while (*str != '\0') {
length++;
str++;
}
return length;
}
```
相关问题
C++用指针变量编写下列处理函数: 字符串拼接函数 字符串比较函数 取字符串长度函数
1. 字符串拼接函数
```c
void string_concat(char *str1, char *str2) {
while (*str1 != '\0') {
str1++;
}
while (*str2 != '\0') {
*str1 = *str2;
str1++;
str2++;
}
*str1 = '\0';
}
```
2. 字符串比较函数
```c
int string_compare(char *str1, char *str2) {
while (*str1 != '\0' && *str2 != '\0') {
if (*str1 != *str2) {
return (*str1 > *str2) ? 1 : -1;
}
str1++;
str2++;
}
if (*str1 == '\0' && *str2 == '\0') {
return 0;
} else {
return (*str1 > *str2) ? 1 : -1;
}
}
```
3. 取字符串长度函数
```c
int string_length(char *str) {
int length = 0;
while (*str != '\0') {
length++;
str++;
}
return length;
}
```
使用指针作为参数,编写函数求字符串的长度。在主函数输入字符串并输出其长度。
好的,以下是使用指针作为参数,编写函数求字符串长度的示例:
```c++
#include <iostream>
using namespace std;
int string_length(const char* str) {
int length = 0;
while (*str != '\0') {
length++;
str++;
}
return length;
}
int main() {
const char* str = "Hello, world!";
int length = string_length(str);
cout << "Length of \"" << str << "\" is " << length << endl;
return 0;
}
```
这里定义了一个名为 `string_length` 的函数,它使用一个指向字符的指针 `str` 作为参数。在函数体内,通过遍历指针所指向的字符数组,逐个字符判断其是否为字符串结尾的空字符 `'\0'`,从而计算字符串的长度。最终将长度值返回给调用方。
在 `main` 函数中,我们定义一个指向字符串常量的指针 `str`,并将其作为参数传递给 `string_length` 函数。然后,将返回的字符串长度存储在整型变量 `length` 中,并输出到标准输出流中。
该程序的输出结果应该是:
```
Length of "Hello, world!" is 13
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)