●例題:文字列の長さを表示するプログラム●
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main(){
char x[100];
int len;
printf("string=");
scanf("%s", x);
len = strlen(x);
printf("strlen(%s)=%d\n", x, len);
return 0;
}
******実行例******
string=impossible
strlen(impossible)=10
続行するには何かキーを押してください . . .
●例題:文字列の連結●
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main(){
char s1[80], s2[80];
printf("s1=");
scanf("%s", s1);
printf("s2=");
scanf("%s", s2);
strcat(s1, s2);
printf("s1=%s,s2=%s\n", s1, s2);
return 0;
}
******実行例******
s1=abcd
s2=efgh
s1=abcdefgh,s2=efgh
続行するには何かキーを押してください . . .
●例題:文字列の比較●
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main(){
char s1[80], s2[80];
int n;
printf("s1=");
scanf("%s", s1);
printf("s2=");
scanf("%s", s2);
n = strcmp(s1, s2);
if (n < 0)printf("%s < %s\n", s1, s2);
else if (n == 0)printf("%s == %s\n", s1, s2);
else if (n>0)printf("%s > %s\n", s1, s2);
return 0;
}
******実行例******
s1=interesting
s2=exiting
interesting > exiting
続行するには何かキーを押してください . . .
●練習問題1●
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<string.h>
int main(){
char x[50];
printf("string=");
scanf("%s", x);
strcat(x, x);
printf("strings = %s\n", x);
return 0;
}
******実行結果******
string=abc
strings = abcabc
続行するには何かキーを押してください . . .
●練習問題3●
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
int main(){
char x[100],s;
int a, i, j;
printf("string = ");
scanf("%s", x);
a = strlen(x);
for (i = a-1; i >= 0; i--){
for (j = 0; j <= i - 1; j++){
s = x[j];
x[j] = x[j + 1];
x[j + 1] = s;
}
}
printf("文字を入れ替えると、reverse string=%s\n", x);
return 0;
}
******実行例******
string = practice
文字を入れ替えると、reverse string=ecitcarp
続行するには何かキーを押してください . . .