我正在上编程课程但是在我的任务的一小部分中我无法弄清楚。到目前为止,我已经写了所有需要的东西,我的代码是:
#include <stdio.h>
#include <string.h>
int main (void)
{
unsigned int length;
unsigned int length2;
char s1[15], s2[15];
puts("Hi! Enter a word to calculate its length!: ");
gets(s1);
length = strlen(s1);
printf("\n-> %s has %d characters!", s1, length);
puts("\n\nEnter another word to calculate its length!: ");
gets(s2);
length2 = strlen(s2);
printf("\n-> %s has %d characters!", s2, length2);
if(strcmp(s1,s2)==0)
{
puts("\n\n-> Words are equal!");
}
if(strcmp(s1,s2)<0)
{
puts("\n\n-> The second word is greater than the first one!");
}
if(strcmp(s1,s2)>0)
{
puts("\n\n-> The first word is greater than the second one!");
}
puts("\n\n...\n\n");
char _add[15];
puts("Type a word to add the first word!");
gets(_add);
strcat(s1, _add);
printf("\n%s added to the first word. Now the first word is:\n",_add);
puts(s1);
length = strlen(s1);
printf("\nNow the first word(%s) has %d characters!", s1, length);
char repl = '!';
//chrstr????
return 0;
}
我希望将第三个连续符号替换为&#39;!&#39;符号并显示新的s2。但我仍然坚持用替换部分(用chrsts ???),我怎样才能用#34替换它?第三个连续符号&#34;
编辑//另一个问题是我应该确认s2有6个或更多字符..我该怎么做?
答案 0 :(得分:0)
&#34;如何用第3个连续符号取代它&#34;要替换s2
中的第3个字符,您可以使用array indexing,即将行\\chrstr????
替换为:
s2[2] = '!';
(并打印出来,如果那是你想要的)
关于如何确认s2有6个或更多字符,只需使用if语句:
if (length2 < 6) {
/* do something to indicate string is too small */
}
答案 1 :(得分:0)
关于如何确认S2有6个或更多字符的问题,可能是:
if(strcmp(s2)>=6)
{
puts("\n\n-> S2 has 6 or more characters!!!");
}
现在,如果你想识别你的第三个角色,那就是这样的:
#include<stdio.h>
#include<string.h>
int main(){
char s2[20];
char third;
printf("Hi! Enter a word so i can tell u its third character: ");
gets(s2);
third = s2[2];//it starts in 0, so your 3rd char is number "2"
printf("\n-> The 3rd character is: %c", third);
}
答案 2 :(得分:-1)
将第三个连续字符更改为“!”的可能算法(如果我理解正确的话):
1. Set S2 iteration index (IDX) to 0
2. While length of S2 > IDX + 2 do
2.1 If S2[IDX] == S2[IDX+1] == S2[IDX+2] then
2.1.1 S2[IDX+2] = '!'
2.1.2 IDX = IDX + 3
2.2 Else
2.2.1 IDX = IDX + 1
关于s2
有6个或更多字符的验证:
if (strlen(s2) < 6)
{
// error message
}