华科机考:字符串连接

输入描述: 每一行包括两个字符串,长度不超过100。

输出描述: 可能有多组测试数据,对于每组数据, 不借用任何字符串库函数实现无冗余地接受两个字符串,然后把它们无冗余的连接起来。 输出连接后的字符串。

输入例子: abc def

输出例子: abcdef

要求:1.无冗余地接受两个字符串

         2.无冗余的连接

显然像以前那样随便定义一个固定大小的数组是不行的(这是大一养成的恶习)o(╯□╰)o

当然用c++的string类,实现这两点非常简单.

代码:

#include <iostream>

using namespace std;

int main(){  
    string a,b;   
    while(cin>>a>>b){   
       cout<<a+b<<endl;  
       }   
   return 0; 
}

不过咱听说华科复试机考只能用c 所以还是老实用malloc函数开辟内存吧

代码:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;

int main(){
    char *str1,*str2;
    char *str;
    char c;
    int i,length1,length2,tmp;
   // while(1){
    i=0;
    str1=(char *)malloc(sizeof(char));
    str2=(char *)malloc(sizeof(char));
    while((c=getchar())!=' '){//接受第一个字符串
    str1[i]=c;//接受该字符
    str1=(char *)realloc(str1,(i+2)*sizeof(char));//准备接受下一个字符
    i++;
    }
    length1=i;
    i=0;
    while((c=getchar())!='
'){//接受第二个字符串
    str2[i]=c;//接受该字符
    str2=(char *)realloc(str2,(i+2)*sizeof(char));//准备接受下一个字符
    i++;
    }
    length2=i;
    str=(char *)malloc((length1+length2+1)*sizeof(char));
    i=0;
    while(i<=length1-1){
     str[i]=str1[i];
     i++;
    }
    tmp=i;
    i=0;
    while(i<=length2-1){
     str[tmp++]=str2[i];
     i++;
    }
    str[tmp]='';
    cout<<str<<endl;
    free(str1);
    free(str2);
    free(str);
    //}
  return 0;
}

通过malloc和realloc函数实现了字符串无冗余接受,但是呢,这个代码过不了(o(╯□╰)o),因为没法实现输入多组数据,不过本身这些题本身是由华科上机题改动过来的
这样写应该没问题。

还有一点要强调一下,如果你想用printf()或者是cout输出字符串时,需要在字符串最后面加上一个''。当然你也可以不加,那就用一个循环将字符一个一个的输出(o(╯□╰)o)

平时我们在定义一个字符数组时没有考虑到这个问题是因为,一般来说定义的固定数组的大小要大于输入的串长度,剩下空缺的位置,系统会自动转为''诶。

吐槽一下:在网上荡了荡代码,发现几乎都是先定义两个固定大小的数组,再开始撸代码。

原文地址:https://www.cnblogs.com/mlgjb/p/6657448.html