まとめ:基本的な文字列関数
CoddyのCジャーニー「Logic & Flow」セクションの一部 — レッスン 19/63。
チャレンジ
簡単単語のペアを処理し、これまでに学んだすべての主要な文字列関数を実演するCプログラムを作成してください。プログラムは以下の処理を行う必要があります:
- 処理する単語ペアの数を示す整数
nを読み込む - 各単語ペアについて:
- 入力から1つ目の単語を読み込む
- 入力から2つ目の単語を読み込む
strlen()を使用して各単語の長さを計算し、表示するstrcmp()を使用して2つの単語を比較し、それらが "identical"(同一)か "different"(異なる)かを表示するstrcpy()とstrcat()を使用して、1つ目の単語、スペース、2つ目の単語を連結した結合文字列を作成する- 結合された文字列を表示する
- すべてのペアを処理した後、最も長い結合文字列を作成したペアを見つけて表示する
文字列関数を使用するために <string.h> ヘッダーをインクルードすることを忘れないでください。
出力は以下の形式で結果を表示する必要があります:
Word 1: [word1] (Length: [length1])
Word 2: [word2] (Length: [length2])
Comparison: [identical/different]
Combined: [word1 word2]
Word 1: [word1] (Length: [length1])
Word 2: [word2] (Length: [length2])
Comparison: [identical/different]
Combined: [word1 word2]
...
Longest combined string: [longest_combined_string]例えば、入力が以下の場合:
3
hello
world
test
test
programming
language出力は以下のようになります:
Word 1: hello (Length: 5)
Word 2: world (Length: 5)
Comparison: different
Combined: hello world
Word 1: test (Length: 4)
Word 2: test (Length: 4)
Comparison: identical
Combined: test test
Word 1: programming (Length: 11)
Word 2: language (Length: 8)
Comparison: different
Combined: programming language
Longest combined string: programming languageこのチャレンジでは、長さ計算のための strlen()、文字列比較のための strcmp()、そして文字列連結のための strcpy() と strcat() を組み合わせて、複数の文字列ペアを処理する包括的なプログラムを作成する理解度をテストします。
自分で試してみよう
#include <stdio.h>
#include <string.h>
int main() {
int n;
scanf("%d", &n);
char word1[100], word2[100];
char combined[200];
char longest_combined[200] = "";
// TODO: ここにコードを記述してください
// 各単語のペアを処理し、最も長い結合文字列を見つけます
return 0;
}