将源字符串 n 个字符连接到 C 中目标字符串
问题
编写一个 C 程序,使用 strncat 库函数将 n 个字符从源字符串连接到目标字符串
解决方案
strcat 函数
此函数用于组合或连接两个字符串。
目标字符串的长度必须大于源字符串。
最终的连接字符串位于源字符串中。
语法
strcat (Destination String, Source string);
示例 1
#include <string.h>
main(){
char a[50] = "Hello";
char b[20] = "Good Morning";
clrscr ( );
strcat (a,b);
printf("concatenated string = %s", a);
getch ( );
}输出
Concatenated string = Hello Good Morning
strncat 函数
此函数用于将一个字符串的 n 个字符组合或连接到另一个字符串。
目标字符串的长度必须大于源字符串。
最终的连接字符串位于目标字符串中。
语法
strncat (Destination String, Source string,n);
示例 2
#include <string.h>
main ( ){
char a [30] = "Hello";
char b [20] = "Good Morning";
clrscr ( );
strncat (a,b,4);
a [9] = ‘\0’;
printf("concatenated string = %s", a);
getch ( );
}输出
Concatenated string = Hello Good.
示例 3
#include<stdio.h>
#include<string.h>
void main(){
//Declaring source and destination strings//
char source[45],destination[50];
//Reading source string and destination string from user//
printf("Enter the source string :");
gets(source);
printf("Enter the destination string before :");
gets(destination);
//Concatenate all the above results//
destination[2]='\0';
strncat(destination,source,2);
strncat(destination,&source[4],1);
//Printing destination string//
printf("The modified destination string :");
puts(destination);
}输出
Enter the source string :TutorialPoint Enter the destination string before :C Programming The modified destination string :C Tur
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP