#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
void replaceSubstring(char *str, char *substr);
int main()
{
int doloop = 1;
char *str = (char *)(malloc(100));
if (str == NULL)
{
printf("No memory allocated");
return;
}
char *substr = (char *)(malloc(100));
if (substr == NULL)
{
printf("No memory allocated");
return;
}
// we gets the text and substring, then we check if the substring is in the text the we change the letters from small to capital .
while (doloop)
{
printf("Enter Text: ");
gets_s(str, 100);
//empty text
if (*str == '\0')
{
printf("Finish!\n");
doloop = 0;
return;
}
printf("Enter substring: ");
gets_s(substr, 100);
//empty substring
if (*substr == '\0')
{
printf("Finish!\n");
doloop = 0;
return;
}
if (*substr)
replaceSubstring(str, substr);
puts(str);
}
free(substr);
free(str);
_getch();
return 0;
}
/*Function name: replaceSubstring
Input: char *str, char *substr
Output: upercase letter
Algorithm: we used for loop to check every letter if its english letter, and then we replace from lower case to uper case*/
void replaceSubstring(char *str, char *substr)
{
int i, len;
char *p;
p = strstr(str, substr);
len = strlen(substr);
while (p)
{
for (i = 0; i < len; i++)
{
// we check if the letters is small english letters
if (*p <= 'z'&&*p >= 'a')
{
*p = *p - 32; // from small letter to capital letter
p++;
}
//else p++;
}
p = strstr(str, substr);
replaceSubstring(str, substr);
}
}
该代码应要求用户输入例如:替换出现的“ r”
然后要求用户输入子字符串,例如: R
然后,代码应检查在文本中找到此子字符串的位置并将其从小写改为大写,但是在这种情况下,当我们输入R时在文本中找不到它,因此答案应与我们输入的文本相同没有改变。 但是当我输入Substring时,代码停止了!