Recursive function s: Remove substring from string in C - c

So I'm supposed to write a program that removes every occurence of substring p from string s, and then print it, using a recursive function, and I'm all out of ideas, so if anyone knows how, let me know. This is as far as I've got:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
void remove(char *s, char *p)
{
char *c=strstr(s,p);
if(c == 0)
return;
}
int main()
{
char s[100], p[50];
printf("Enter string and substring: ");
scanf("%s %s", s, p);
remove(s, p);
printf("New string: %s", s);
getchar();
getchar();
return 0;
}

This should work:
#include <stdio.h>
#include <string.h>
void removestr(char *s, char *p, int len)
{
char *c=strstr(s,p); // strstr returns the address where the substring starts
if(c) {
strcpy(c,c+len); //if the substring was found, copy over it the
//string starting from where the substring ends e.g. (assume
//p="the") thisthestring => thisstring
removestr(s,p,len); //call the function again
}
else
return; //stop if no substring was found
}
int main(void)
{
char s[100], p[50];
printf("Enter string and substring: ");
if(scanf("%99s",s)==1 && scanf("%49s",p)==1) //it's important to check the input
// also %s is vulnerable to overflow, specify the sizes to be safe
removestr(s, p , strlen(p));
printf("New string: %s", s);
getchar();
getchar();
return 0;
}

Related

Using _flushall() repaired my code, and I don't understand why

I wrote a function that removes a given char from a string.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* input_long(void);
void removeChar(char str[], char ch);
void main()
{
char *str, ch;
str=input_long();
printf("\nplease enter a char to be removed from the string: ");
scanf("%c", &ch);
removeChar(str, ch);
printf("the string after the removal is %s \n", str);
free(str);
}
void removeChar(char str[], char ch) //this function removing a given char from a given string//
{
int i,j = 0;
for (i = 0; str[i] != '\0'; i++) //looping the string until its end//
{
if (str[i] != ch) //by that we ensure the char will be erased from the string //
{
str[j] = str[i];
j++;
}
}
str[j]='\0'; //the end of the new string after the whole process//
}
char* input_long(void) //this function gets a string dynamically allocated//
{
char tempstr[80], *str;
printf("enter a string\n");
gets(tempstr);
str=(char*)malloc((strlen(tempstr)+1)*sizeof(char));
strcpy(str,tempstr);
return str;
}
My code didn't run well; when I ran it, it seemed to lead the statement which asks the user to enter a string. I repaired the code by adding _flushall() , and now the code is running well:
_flushall
str=input_long();
printf("\nplease enter a char to be removed from the string: ");
scanf("%c", &ch);
I don't really understand why adding that statement indeed repaired it.

Returning char[] value in C

I m trying to understand how to return a string in c. I tried different ways but didnt manage to do it. Could you edit this code?
char dublicate(char str[])
{
return str[20];
}
int main()
{
char str[20];
scanf("%s", &str);
printf("%s", dublicate(str));
return 0;
}
You can do something like this. string_dupe creates a copy of the string sent from scanf, which must use malloc() or strdup() to allocate space for it on the heap. The pointer to the first element in duplicate is then returned to main and printed out. Then free() is executed to release the memory allocated for the string on the heap.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 20
char *string_dupe(char *string);
int
main(void) {
char str[SIZE];
char *strcopy = NULL;
printf("Enter string: ");
scanf("%s", str);
strcopy = string_dupe(str);
printf("\nYour copied string: %s", strcopy);
free(strcopy);
return 0;
}
char
*string_dupe(char *string) {
char *duplicate = NULL;
if ((duplicate = malloc(strlen(string)+1)) == NULL) {
fprintf(stderr, "Memory not allocated\n");
exit(EXIT_FAILURE);
}
strcpy(duplicate, string);
return duplicate;
}
Change the return type of dublicate, and change how you read into str in your call to scanf:
char *dublicate(char str[])
{
return str;
}
int main() {
char str[20];
scanf("%s", str);
printf("%s", dublicate(str));
return 0;
}
A string is essentially a pointer to a character that is the first character of the string. (The end of the string is determined by the '\0' character.) So all you have to return is a char pointer.

C function to capitalize the first character of a pointer string

I want to capitalize the first character of a pointer string.
For example, input: john
Output: John
I can do it with arrays (s[0] = toUpper(s[0]), but is there a way to do it with pointers?
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX 30
int transform(char *s)
{
while (*s != '\0')
{
*s = toupper(*s);
s++;
}
return *s;
}
int main()
{
printf("String: ");
char *s[MAX];
getline(&s,MAX);
transform(s);
printf("Transformed char: %s", &s);
}
int getline(char *s, int lim)
{
int c;
char *t=s;
while (--lim>0 && (c=getchar())!=EOF && c!='\n') *s++=c;
*s='\0';
while (c!=EOF && c!='\n')
c=getchar();
return s-t;
}
This code turns the whole string to upper case.
Your transform function is looping through the entire string and running toupper on each one. Just run it on the first character:
void transform(char *s)
{
*s = toupper(*s);
}
Also, you declare s in main as an array of pointers to char. You just want an array of char:
int main()
{
printf("String: ");
char s[MAX];
getline(s,MAX); // don't take the address of s here
transform(s);
printf("Transformed char: %s", s); // or here
}
You want to move main to the end of the file as well, so that getline is defined before it is called.
Easy solution:
void transform(char* p) {
//Only first character
*p = toupper(*p);
}
//Call like that:
char str[] = "test";
transform(str); //str becomes: "Test"

conflicting types for function returning a char array

Here's my code:
#include <stdio.h>
#include <string.h>
char input_buffer[1000];
void get_substring(){
int i;
int length;
printf("Please enter a string:\n");
scanf("%[^\n]s", input_buffer);
printf("Index of first character of substring:\n");
scanf("%d", &i);
printf("Length of substring:\n");
scanf("%d", &length);
printf("Substring is %.*s ", length, input_buffer + i);
}
int main(void) {
// your code goes here
//get_substring(0,4);
get_substring();
return 0;
}
That's my current code, I want to return a pointer of the input, instead of just displaying the substring. Sorry for the confusion everyone.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* getSubstring(char* str,size_t start, size_t length)
{
// determine that we are not out of bounds
if(start + length > strlen(str))
return NULL;
// reserve enough space for the substring
char *subString = malloc(sizeof(char) * length);
// copy data from source string to the destination by incremting the
// position as much as start is giving us
strncpy(subString, str + start, length);
// return the string
return subString;
}
int main(int argc, char* argv[])
{
char *str = "Hallo Welt!";
char *subStr = getSubstring(str,0,20);
if(subStr != NULL)
{
printf("%s\n",subStr);
free(subStr);
}
}
This solution should give you a hint how you would start with such a problem.

I need to know how many times a string appears within another one! Using C

Well, the title already says what I need. I tried to use a loop but it didn't go well, so, I came for your help guys!
Here's my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char word[31], word2[31];
int size1, size2;
int i, j, k; // control
int count = 0;
printf ("\nInput the first word");
scanf ("%s", word);
printf ("\nInput the second word: ");
scanf (" %s", word2);
// I tried to make a loop through the first string and if it matches a letter, it would loop through the others (if they are equal, we have a substring), but failed to put it on the `for` loop
printf ("'%s' appears %d times within '%s'", word2, count, word);
return 0;
}
strstr is a useful function, it shortens your code considerably; when you find a match, just try again with the rest of the string;
#include <string.h>
#include <stdio.h>
int main()
{
const char* source = "aabaa";
const char* string2find = "aa";
int occurrences;
const char *ptr, *lastfind = NULL;
for(ptr=source; (lastfind=strstr(ptr, string2find)); ptr=lastfind+1)
occurrences++;
printf("%d\n", occurrences);
return 0;
}
...or if you're really set on doing it without string.h functions, the code gets a bit more verbose;
#include <string.h>
#include <stdio.h>
int main()
{
const char* source = "aaabaa";
const char* string2find = "aa";
int count=0;
const char *position;
for(position=source; *position; position++) {
int comparepos, equal=1;
for(comparepos=0; string2find[comparepos]; comparepos++) {
if(position[comparepos] != string2find[comparepos]) {
equal = 0;
break;
}
}
count+=equal;
}
printf("%d\n", count);
return 0;
}
Use strstr to find occurence of string in other string:
#include <stdio.h>
#include <string.h>
int main () {
char* a = "aaaa";
char* b = "aa";
char* c;
int count = 0;
for(c = a; *c; c++){
if(strstr(c, b)){
count++;
}
}
printf("count %d\n", count);
}
Also, use strlen to find length of a string..

Resources