游客 Signup | Login
中文 | En

1349 - 算法4-4:字符串插入

将一个字符串插入到另一个字符串当中。算法描述如下:

<span style="font-size:10.5pt;">图:字符串插入算法</span>

Input

输入只有一行,两个字符串(stra,strb)和一个整数 i。字符串仅由英文大小写字母或数字组成。输入的字符串长度不超过127。

Output

将后一个字符串插入到前一个字符串的第i个字符前。输出插入后的结果。

Examples

Input

strng i 4

Output

string

Hint

提示:
由于HString是由字符指针和整数构成,因而其结构和操作相对比较简单。但是,对于输入,可能需要多余的操作了。首先使用C字符串来获取字符串,然后获得输入字符串的长度,然后再分配内存。分配的长度要比输入的字符串的长度大1,你知道的。同时上述算法插入时也要注意字符串结尾(上述算法需要补充)。
注意输入的字符串长度不大于127,但结果字符的字符串长度可能大于127。
总结:
通过熟悉这个算法,能够理解C语言字符串和C++中的string类的实现了。

Solution C

#include <stdio.h>
#include <string.h>

void insert (char *s,  char  *t,  int i)
{
	char string[300],  *temp =string;
	
	if  (!strlen (s))
		strcpy (s,  t);
	else   if (strlen (t))  {
		strncpy (temp, s, i);
		strcat (temp, t) ;
		strcat (temp,  (s + i ));
		strcpy (s, temp );
	}
}
int main ()
{
	char s[128];
	char t[128];
  int i;
  scanf("%s %s %d",s,t,&i);
	insert(s,t,i-1);
	printf("%s",s);
	printf ("\n");
}

Solution C++

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef int Status;
#define ERROR 0
#define OK 1
typedef struct {
	char * ch;		// 若是非空串,则按串长分配存储区,否则 ch 为 NULL
	int length;		// 串长度
}HString;

void ScanHString(HString& str){
	// 读取HString类字符串
	char chrstr[128];
	scanf("%s", chrstr);	//读取一个C字符串
	str.length = strlen(chrstr);	// 获得该字符串的长度
	str.ch = (char *)malloc((str.length+1)*sizeof(char));	// 分配内存
	strcpy(str.ch, chrstr);	// 将字符串从C字符串拷贝到HString中
}

void PrintHString(HString str){
	// 输出HString字符串
	printf("%s", str.ch);
}

Status StrInsert(HString &S, int pos, HString T) {  // 算法4.4
   // 1≤pos≤StrLength(S)+1。在串S的第pos个字符之前插入串T。
   int i;
   if (pos < 1 || pos > S.length+1)  // pos不合法
      return ERROR;
   if (T.length) {    // T非空,则重新分配空间,插入T
      if (!(S.ch = (char *)realloc(S.ch,(S.length+T.length+1)*sizeof(char))))
         return ERROR;
      for (i=S.length-1; i>=pos-1; --i)  // 为插入T而腾出位置
         S.ch[i+T.length] = S.ch[i];
      for (i=0; i<T.length; i++)         // 插入T
         S.ch[pos-1+i] = T.ch[i];
      S.length += T.length;
   }
   S.ch[S.length] = '\0';		// 注意字符结尾
   return OK;
} // StrInsert

int main(){
	HString stra, strb;		// 定义两个字符串
	int pos;				// 定义插入的位置
	ScanHString(stra);		// 读取字符串
	ScanHString(strb);
	scanf("%d", &pos);		// 读取位置
	StrInsert(stra, pos, strb);	// 字符串插入
	PrintHString(stra);		// 输出结果

	return 0;
}

Hint

提示:
由于HString是由字符指针和整数构成,因而其结构和操作相对比较简单。但是,对于输入,可能需要多余的操作了。首先使用C字符串来获取字符串,然后获得输入字符串的长度,然后再分配内存。分配的长度要比输入的字符串的长度大1,你知道的。同时上述算法插入时也要注意字符串结尾(上述算法需要补充)。
注意输入的字符串长度不大于127,但结果字符的字符串长度可能大于127。
总结:
通过熟悉这个算法,能够理解C语言字符串和C++中的string类的实现了。
Time Limit 1 second
Memory Limit 32 MB
Discuss Stats
上一题 下一题