回 帖 发 新 帖 刷新版面

主题:字符串常量的连接

The C Programming Language 中提到 字符串常量连接的概念, 可是却没有相关的实例。用股沟也搜不到相关的知识。麻烦各位大侠能告诉小弟这方面的知识。高分悬赏!

回复列表 (共4个回复)

沙发

string str1="abc";
string str2="def";
string str=str1+str2;  //str=="abcdef",把str1和str2相加即可完成连接

板凳

那你的搜索能力也太差了吧
还有不用string 的重载+   用strcat
原型:extern char *strcat(char *dest,char *src);
  用法:#include <string.h>
  功能:把src所指字符串添加到dest结尾处(覆盖dest结尾处的'\0')并添加'\0'。
  说明:src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串。
  返回指向dest的指针。
  举例:
  // strcat.c
  #include <syslib.h>
  #include <string.h>
  main()
  {
  char d[20]="Golden Global";
  char *s=" View";
  clrscr();
  strcat(d,s);
  printf("%s",d);
  getchar();
  return 0;
  }
  程序执行结果为:
  Golden Global View

3 楼

有三种做法:
1、自己写个函数把已知的两个字符串连接起来;
2、用c标准库中提供的函数strcat(char *a,char *b)将a与b连接起来存到a中,像2楼那样做!
3、用c++库中的string类,就像一楼的那样,这种最为简单。

自己写个函数,这样实现:

[code=c]
#include<stdio.h>

int main()
{
   char s1[50],s2[50];
   int i=0,j=0;
   printf("\nInput s1:");
   scanf("%s",s1);
   printf("\nInput s2:");
   scanf("%s",s2);
   while(s1[i]!='\0')//计算s1的长度为i!
        i++;
   while(s2[j]!='\0')  //用while语句实现将s2连接到s1后面。
       s1[i++]=s2{j++};
   s1[i]='\0';
  printf("The new string is : %s",s1);
[/code]

4 楼

[quote]有三种做法:
1、自己写个函数把已知的两个字符串连接起来;
2、用c标准库中提供的函数strcat(char *a,char *b)将a与b连接起来存到a中,像2楼那样做!
3、用c++库中的string类,就像一楼的那样,这种最为简单。

自己写个函数,这样实现:

[code=c]
#include<stdio.h>

int main()
{
   char s1[50],s2[50];
   int i=0,j=0;
   printf("\nInput s1:");
   scanf("%s",s1);
   printf("\nInput s2:");
   scanf("%s",s2);
   while(s1[i]!='\0')//计算s1的长度为i!
        i++;
   while(s2[j]!='\0')  //用while语句实现将s2连接到s1后面。
       s1[i++]=s2{j++};
   s1[i]='\0';
  printf("The new string is : %s",s1);
[/code][/quote]
这方法段代码的问题在于目标串的长度可能超过50,比较好的做法是开一个新串申请足够的空间,然后把两个串顺序拷进去

我来回复

您尚未登录,请登录后再回复。点此登录或注册