编写程序:用gets和puts实现两字符串前半段合并并输出
Solution for Combining First Halves of Two Strings
Got it, let's put together a C program that does exactly what you need. We'll use gets() for input and puts() for output as requested, and walk through how it works step by step.
Step-by-Step Breakdown
- First, declare three string buffers:
CH1,CH2, andCH3. Make sureCH3is large enough to hold the combined first halves of the other two strings. - Use
gets()to read input strings intoCH1andCH2. Quick note: Whilegets()is required here, it's important to mention thatgets()is unsafe in modern C because it doesn't check buffer boundaries—for real-world code, usefgets()instead. - Calculate the length of each string with
strlen()to find the halfway point. For a string of lengthn, the first half will be the firstn/2characters (integer division handles both even and odd lengths naturally). - Copy the first half of
CH1intoCH3, then append the first half ofCH2toCH3. Don't forget to add a null terminator ('\0') toCH3to make it a valid C string. - Finally, use
puts()to print the resultingCH3.
Complete Program Code
#include <stdio.h> #include <string.h> int main() { // Define buffers for input strings and the result char CH1[100], CH2[100], CH3[200]; int len1, len2, current_index = 0; // Read input strings using gets() printf("Enter first string (CH1): "); gets(CH1); printf("Enter second string (CH2): "); gets(CH2); // Calculate lengths of the input strings len1 = strlen(CH1); len2 = strlen(CH2); // Copy first half of CH1 to CH3 for (int i = 0; i < len1 / 2; i++) { CH3[current_index++] = CH1[i]; } // Append first half of CH2 to CH3 for (int j = 0; j < len2 / 2; j++) { CH3[current_index++] = CH2[j]; } // Add null terminator to make CH3 a valid string CH3[current_index] = '\0'; // Print the result using puts() printf("\nResulting string (CH3): "); puts(CH3); return 0; }
Example Output
Enter first string (CH1): HelloWorld Enter second string (CH2): StackOverflow Resulting string (CH3): HelloStack
(Explanation: "HelloWorld" is 10 characters, so its first half is the first 5: "Hello". "StackOverflow" is 13 characters, so its first half is the first 6: "Stack". Combining them gives "HelloStack".)
Alternative Concise Approach
Instead of manual loops, you can use strncpy() for cleaner code:
#include <stdio.h> #include <string.h> int main() { char CH1[100], CH2[100], CH3[200]; int len1, len2; printf("Enter first string (CH1): "); gets(CH1); printf("Enter second string (CH2): "); gets(CH2); len1 = strlen(CH1); len2 = strlen(CH2); // Copy first half of CH1 strncpy(CH3, CH1, len1 / 2); // Append first half of CH2 strncpy(CH3 + len1 / 2, CH2, len2 / 2); // Add null terminator CH3[len1/2 + len2/2] = '\0'; printf("\nResulting string (CH3): "); puts(CH3); return 0; }
内容的提问来源于stack exchange,提问作者rtg2.
相关产品推荐
相关产品推荐

