本文目錄一覽:
c語言you
是其中的一個字符還是整個數組
數組的話用for
字符的話需要藉助第三個臨時變量
c = a;
a= b;
b= c;
c語言 描述 編寫一個程序實現將字符串中的所有”you”替換成”we”
編程水平有限 還沒看到指針 只用了前面的內容 調試通過了
#includestdio.h
#includestring.h
int main()
{
char str[1000];
int i=0,strlong,flag[333],n; //strlong用來儲存str的長度,flag用來儲存you中u的位置
printf(“Please input string!\n”);
while((scanf(“%c”,str[i++])!=EOF)i=1000) //輸入後按Enter,再按ctrl+z
{
continue;
}
strlong=strlen(str);
for(i=0,n=0;i=strlong;i++)
{
if(str[i]==’y’||str[i]==’Y’)
{
if(str[i+1]==’o’||str[i+1]==’O’)
{
if(str[i+2]==’u’||str[i+2]==’U’) //判斷是否為單詞you
{
if(str[i]==’Y’)
str[i]=’W’;
else //保證字母大小寫相同
str[i]=’w’;
if(str[i+1]==’O’)
str[i+1]=’E’;
else
str[i+1]=’e’;
flag[n++]=i+2; //儲存u的位置,便於將u覆蓋
}
}
}
}
for(n=0;flag[n]!=’\0′;n++) //這裡就是將u後面的字符向前移動一位
{ //替換一個you後因為後面的字符整體前移了
if(n==0)
i=flag[n];
else //所以flag中儲存的u的位置就要減去1,替換兩個後
i=flag[n]-n; //整體前移兩位,就要減去2,以此類推
for(;i=strlong;i++)
{ //不清楚的話你可以吧for後的if…..else…去掉
str[i]=str[i+1]; //直接把i=flag[n]放在第二個for(i=flag[n];;)中
}
}
printf(“%s”,str);
return 0;
}
題目描述 (請用C語言) 編寫一個C程序實現將字符串中的所有單詞”you”替換成”we” 輸入
#include “stdio.h”
#include “string.h”
bool IsSeparator(char ch)
{
return (!((ch = ‘a’ ch = ‘z’) || (ch = ‘A’ ch = ‘Z’)));
}
char* GetFirstWord(char *sentence)
{
char word[100];
int i;
for(i = 0; i 100; i++)
word[i] = ‘\0’;
for(i = 0; sentence[i] !IsSeparator(sentence[i]); i++)
word[i] = sentence[i];
return word;
}
void main()
{
char sentence[] = “you are what you do”, word[101];
char *p;
int i, j;
printf(sentence);
printf(“\n”);
i = 0;
p = sentence;
while(*p)
{
strcpy(word, GetFirstWord(p));
if(strcmp(word, “you”) != 0)
{
for(j = 0; j strlen(word); j++)
sentence[i++] = *(p++);
}
else
{
p = p + 3;
sentence[i++] = ‘w’;
sentence[i++] = ‘e’;
}
sentence[i++] = *p;
if(*p) p++;
}
printf(sentence);
printf(“\n”);
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/196790.html