C言語のstrncpy()関数とは何ですか?
Cライブラリ関数char* strncpy(char * dest、const char * src、size_t n) src が指す文字列から、最大n文字をコピーします 宛先へ 。 srcの長さがnの長さよりも短い場合、destの残りの部分はnullバイトで埋められます。
文字の配列は文字列と呼ばれます。
宣言
以下は配列の宣言です-
char stringname [size];
例-charstring[50];長さ50文字の文字列
初期化
- 単一文字定数の使用-
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’} - 文字列定数の使用-
char string[10] = "Hello":;
アクセス −「\0」に遭遇するまで文字列にアクセスするために使用される制御文字列「%s」があります。
strncpy()関数
-
この関数は、ソース文字列の「n」文字を宛先文字列にコピーするために使用されます。
-
宛先文字列の長さがソース文字列以上です。
構文は次のとおりです-
strncpy (Destination string, Source String, n);
サンプルプログラム
以下はstrncpy()関数のCプログラムです-
#include<string.h>
main ( ){
char a[50], b[50];
printf ("enter a string");
gets (a);
strncpy (b,a,3);
b[3] = '\0';
printf ("copied string = %s",b);
getch ( );
} 出力
上記のプログラムを実行すると、次の結果が得られます-
Enter a string : Hello Copied string = Hel
部分文字列の抽出にも使用されます。
例1
次の例は、strncpy()関数の使用法を示しています。
char result[10], s1[15] = "Jan 10 2010"; strncpy (result, &s1[4], 2); result[2] = ‘\0’
出力
上記のプログラムを実行すると、次の結果が得られます-
Result = 10
例2
strncpyの別の例を見てみましょう。
以下に示すのは、strncpyライブラリ関数-
を使用して、ソース文字列から宛先文字列にn個の文字をコピーするCプログラムです。#include<stdio.h>
#include<string.h>
void main(){
//Declaring source and destination strings//
char source[45],destination[50];
char destination1[10],destination2[10],destination3[10],destination4[10];
//Reading source string and destination string from user//
printf("Enter the source string :");
gets(source);
//Extracting the new destination string using strncpy//
strncpy(destination1,source,2);
printf("The first destination value is : ");
destination1[2]='\0';//Garbage value is being printed in the o/p because always assign null value before printing O/p//
puts(destination1);
strncpy(destination2,&source[8],1);
printf("The second destination value is : ");
destination2[1]='\0';
puts(destination2);
strncpy(destination3,&source[12],1);
printf("The third destination value is : ");
destination3[1]='\0';
puts(destination3);
//Concatenate all the above results//
strcat(destination1,destination2);
strcat(destination1,destination3);
printf("The modified destination string :");
printf("%s3",destination1);//Is there a logical way to concatenate numbers to the destination string?//
} 出力
上記のプログラムを実行すると、次の結果が得られます-
Enter the source string :Tutorials Point The first destination value is : Tu The second destination value is : s The third destination value is : i The modified destination string :Tusi3
-
C言語のstrcmp()関数とは何ですか?
Cライブラリ関数intstrcmp(const char * str1、const char * str2) str1が指す文字列を比較します str2が指す文字列へ 。 文字の配列は文字列と呼ばれます。 宣言 以下は配列の宣言です- char stringname [size]; 例-charstring[50];長さ50文字の文字列 初期化 単一文字定数の使用- char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,&ls
-
C言語のstrcpy()関数とは何ですか?
Cライブラリ関数char* strcpy(char * dest、const char * src) srcが指す文字列をコピーします 宛先へ 。 文字の配列は文字列と呼ばれます。 宣言 以下は配列の宣言です char stringname [size]; 例-charstring[50];長さ50文字の文字列 初期化 単一文字定数の使用- char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}