In: Computer Science
#include <cstring>
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 20;
char str[SIZE];
char str1[SIZE];
int n;
int k =1;
printf("Enter a word: \n");
fgets(str,SIZE,stdin);
printf("Enter another word: \n");
fgets(str1,SIZE,stdin);
if (str1[strlen(str1) - 1] == '\n')
{
str1[strlen(str1)-1] =
'\0';
}
if (str[strlen(str) - 1] == '\n')
{
str[strlen(str)-1] =
'\0';
}
printf("Enter a number between 1 and 20:
\n");
scanf("%d",&n);
strcat(str, " ");
strncat(str, str1,n);
printf("%s", str);
printf("\n");
str[0] = toupper(str[0]);
for (int i = 1; i < strlen(str); i++)
{
str[i] =
tolower(str[i]);
if(str[i-1] == '
')
{
str[i]= toupper(str[i]);
}
}
for (int j = 1; j < strlen(str); j ++)
{
for (int i = 1; i <
strlen(str); i++)
{
//
if(str[i]!= '\0')
{
if(!strstr(str, "here"))
{
k++;
}
if(strchr(str,'\0'))
{
break;
}
}
}
}
cout << "Found "<< k << "
words 'here' in: \n" << str;
return 0;
}
================================================================================
so im practicing working on c++ with c-strings and i when i compile and run this, at the end the loop iterates one time for the entire length of the cstring and i cannot figure out how to end it after finding the 'k' amount of times the word "here" is in the string.
check out the solution.
-------------------------------------------
CODE:
#include <cstring>
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
const int SIZE = 20;
char str[SIZE];
char str1[SIZE];
int n;
int k = 0;
printf("Enter a word: \n");
fgets(str,SIZE,stdin);
printf("Enter another word: \n");
fgets(str1,SIZE,stdin);
if (str1[strlen(str1) - 1] == '\n')
{
str1[strlen(str1)-1] = '\0';
}
if (str[strlen(str) - 1] == '\n')
{
str[strlen(str)-1] = '\0';
}
printf("Enter a number between 1 and 20: \n");
scanf("%d",&n);
strcat(str, " ");
strncat(str, str1,n);
printf("%s", str);
printf("\n");
str[0] = toupper(str[0]);
for (int i = 1; i < strlen(str); i++)
{
str[i] = tolower(str[i]);
if(str[i-1] == ' ')
{
str[i]= toupper(str[i]);
}
}
// loop through all characters in string till strlen-4
for (int i=0; i<=(strlen(str)-4); i++)
{
// search for characters 'here' as here is converted to 'Here' in
above code so check for 'Here' instead ' here'
if(str[i] == 'H' && str[i+1] == 'e' && str[i+2] ==
'r' && str[i+3] == 'e')
k++;
}
cout << "Found "<< k << " words 'here' in : "
<< str;
return 0;
}
--------------------------------------
-----------------------------------------------
OUTPUT :
====================================================