用c语音写一个函数,函数功能如下:将两个字符串组合成一个新的字符串,并且返回这个新的字符串。
时间: 2023-03-08 16:16:46 浏览: 48
答:char *concatenate(char *str1, char *str2) {
char *newStr = (char *)malloc(strlen(str1) + strlen(str2) + 1);
strcpy(newStr, str1);
strcat(newStr, str2);
return newStr;
}
相关问题
C语言编写一个函数,用哈希函数将一个字符串转换成一个整型数组的下标。这个怎么写
可以使用简单的取余算法,将字符串转换成一个整数,再对数组长度进行取余来得到对应的数组下标。例如:
```c
unsigned int hash_function(char* str, int array_size){
unsigned int hash = 0;
int c;
while ((c = *str++)){
hash = c + (hash << 6) + (hash << 16) - hash; //DJB Hash算法
}
return hash % array_size; //取余得到数组下标
}
```
这个函数用DJB Hash算法将字符串转换成一个32位的无符号整数,再将该整数对数组长度取余得到对应的下标。
用C语言编写一个函数,将用户输入的一个数字字符串转换成一个整数,并返回该整数
可以使用库函数 `atoi` 来实现该功能。`atoi` 函数的原型定义在头文件 `stdlib.h` 中,该函数可以将一个字符串转换成一个整数。下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
int str_to_int(char *str)
{
return atoi(str); // 调用 atoi 函数将字符串转换成整数并返回
}
int main()
{
char str[100];
printf("请输入一个数字字符串:");
fgets(str, sizeof(str), stdin); // 从标准输入读取字符串
int num = str_to_int(str);
printf("转换后的整数为:%d\n", num);
return 0;
}
```
上面的代码中,`str_to_int` 函数接受一个指向字符串的指针作为参数,将该字符串转换成整数并返回。在 `main` 函数中,先使用 `fgets` 函数从标准输入读取字符串,然后调用 `str_to_int` 函数将字符串转换成整数,并输出结果。
相关推荐
![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_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)