编写程序:输入两个字符串并连接后,将其中的全部空格移动到串首后输出
例如:输入串1:Today is Friday 串2:You are right
输出: TodayisFridayYouareright(前面有四个空格)
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100], result[200];
int i, j = 0;
// 输入两个字符串
printf("Enter the first string: ");
fgets(str1, 100, stdin);
printf("Enter the second string: ");
fgets(str2, 100, stdin);
// 将两个字符串连接到result数组中
strcat(result, str1);
strcat(result, str2);
// 将空格移动到串首
for(i = 0; result[i] != '\0'; i++) {
if(result[i] == ' ') {
for(j = i; result[j] != '\0'; j++) {
result[j] = result[j+1];
}
result[j-1] = ' ';
i--;
}
}
// 输出结果
printf("The result string is: %s", result);
return 0;
}
参考网络
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
printf("Enter string 1: ");
gets(str1);
printf("Enter string 2: ");
gets(str2);
strcat(str1, str2);
char output_str[200] = "";
int output_idx = 0;
int count = 0;
for (int i = 0; i < strlen(str1); i++) {
if (str1[i] == ' ') {
output_str[output_idx++] = ' ';
count++;
}
}
strcat(output_str, str1);
for (int i = 0; i < strlen(output_str); i++)
{
if(i<count)
printf(" ");
if(i>=count&&output_str[i]!=' ')
printf("%c", output_str[i]);
}
return 0;
}
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100], str2[100], newstr[200];
int i, j;
printf("请输入第一个字符串:");
gets(str1);
printf("请输入第二个字符串:");
gets(str2);
// 将两个字符串连接起来
strcpy(newstr, str1);
strcat(newstr, str2);
// 将空格移动到串首
j = 0;
for (i = 0; newstr[i] != '\0'; i++)
{
if (newstr[i] == ' ')
{
// 将空格移动到串首
for (j = i; j > 0; j--)
{
newstr[j] = newstr[j-1];
}
newstr[0] = ' ';
}
}
printf("连接后的字符串是:%s\n", newstr);
return 0;
}
仅供参考!
#include<stdio.h>
#include<string.h>
int main(void)
{
char s[1024] = { '\0' };
char s1[1024];
char s2[512];
int len1;
static const char *c = " ";
fgets(s1, 510, stdin);
fgets(s2, 510, stdin);
strcpy(s1 + strlen(s1) - 1, s2);
s1[len1 = strlen(s1)] = '\0';
char *p = strtok(s1, c);
while (p)
{
strcat(s, p);
p = strtok(NULL, c);
}
int n = len1 - strlen(s);
while (n--)
putchar(' ');
puts(s);
return 0;
}
不知道你这个问题是否已经解决, 如果还没有解决的话: