c語言字元函數參數
『壹』 用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語言字元長度函數
正確的答案是5,題目選項有誤。
首先strlen()函數返回的長度是不包含'