Ⅰ c語言中如何將一字元串插入另一個字元串中
#include<stdio.h>
void main()
{
void insert(char a[],char b[],int t);
char a[100],b[100];
int t,i,j;
printf("input a string:\n");
gets(a);
printf("inut b string:\n");
gets(b);
printf("input the position to insert:\n");
scanf("%d",&t);
if(t<=0 || t>strlen(a)+1)
{
printf("wrong!.input again");
scanf("%d",&t);
}
insert(a,b,t);
}
void insert(char a[],char b[],int t)
{
int len1,len2;
int i,j,k,l;
char c[100];
len1=strlen(a);
len2=strlen(b);
for(i=0;i<t-1;i++)
c[i]=a[i];
for(j=0;j<len2;j++)
c[i+j]=b[j];
l=0;
for(k=t-1;k<len1;k++)
{
c[i+j+l]=a[k];
l++;
}
c[i+j+l]='\0';
puts(c);
}
另外,站長團上有產品團購,便宜有保證
Ⅱ C語言中,如何在一字元串中插入字元
c[5]只有5個空間無法完全容納字元串"hello",因為這個字元串需要佔用6個字元位置。
所謂自動加'\0'的問題是:你寫在雙引號中的,編譯程序會認為是字元串,會自動為你添加上一個字元串結尾符號0,而不是運行時添加的。
如果你用debug方式運行程序,調試環境自動會把你開設的char
a[5];進行初始化0的工作,這時你再將第1位初始化時,後面的0仍存在就好象字元串結尾已經存在了。如果非debug運行則沒有這個初始化工作。
如果你用字元方式初始化應當寫:char
c[6]={
'h','e','l','l','o','\0'
};
希望對你能有所幫助。
Ⅲ c語言求解。。。。輸入一個字元串,在指定位置插入一個字元
#include"string.h"
#include <stdio.h>
main()
{char a[100],x;
int len,i,wz;
printf("input:\n");
scanf("%d%c%s",&wz,&x,a);
len=strlen(a);
printf("\n");
for(i=len-1;i>=wz-1;i--)
a[i+1]=a[i];
a[wz-1]=x ;
a[len+1]='\0';
printf("%s\n",a) ;
}
輸入的時候注意了,回車結束,例如輸入:4dabcef 結果:abcdef 希望有所幫助 ,WZ表示位置,x表示要插入的字元,a表示字元串,當然你可以判斷輸入的位置是否超過字元串的長度,我就不寫了,推薦下^_^
Ⅳ 用C語言怎麼寫個 字元串插入函數
程序的大體思路可以是這樣:
str1是原字元串,str2是待插入的字元串,position是待插入的位置,我們可以這樣,用一個指針p_cur指向字元串1 str1中的待插入位置position,另一個指針p_end指向字元串1 str1的尾部,每次插入字元前,把str1中從當前位置開始一直到結束字元全部後移一個位置,空出當前位置,然後把要插入的字元放進這個位置,這樣就完成了一個字元的插入,重復這個步驟,直到str2被完全插入。
代碼如下:
#include <stdio.h>
#include <string.h>
void insert_str(char str1[],char str2[],int position)
{
/*
insert_str()函數
功能:將字元串str2插入到str1的position位置處
參數:char str1,char str2 ,int position
返回值:無
*/
int i;
char *p_end,*p_cur,*p;/*p_end指向第一個字元串的尾部,p_cur指向被插入的位置*/
p_end=str1+strlen(str1)-1;
p_cur=str1+position-1;
for(i=0;str2[i]!='\0';i++)
{
for(p=p_end;p>=p_cur;p--)
{
*(p+1)=*p;/*從p_cur到p_end的全部元素後移一個位置,此時p_cur指向的位置就空出來了*/
}
*p_cur=str2[i];/*把字元串2中的字元插入空出來的位置*/
p_cur++;/*p_cur下移一個位置*/
p_end++;/*多了一個字元,因此p_end也下移一個位置*/
}
}
void main()
{
char s1[100],s2[20];
int position;
printf("輸入字元串1:\n");
gets(s1);
printf("輸入插入位置:");
do
{
scanf("%d",&position);
while(getchar()!='\n');/*這一句可以把輸入position的時候輸入的回車去掉*/
}while(position<0||position>strlen(s1));
printf("輸入字元串2:\n");
gets(s2);
insert_str(s1,s2,position);
printf("字元串被插入後變成:\n");
puts(s1);
}
Ⅳ C語言字元插入
#include<stdio.h>
#include<string.h>
#defineN100
voidinsertChar(chars[],charc)
{
intn,i,j;
for(i=0;s[i]!='