How remove fragment from string - c

how remove fragment from string in c?
For example:
int main()
{
char *string = "Qwertyuio pasdf ghjklzxcv bnm";
char *fragment = "pasdf";
}
How cut pasdf but save other?

In your example, you cannot change the content of string.
Here's how to do it properly:
#include <stdio.h>
#include <string.h>
int
main()
{
char *string = strdup("Qwertyuio |pasdf| ghjklzxcv bnm");
char *fragment = "pasdf";
char *w = string;
int length = strlen(string);
printf("%s\n", string);
while (*w)
{
if (!strncmp(w, fragment, strlen(fragment)))
{
length -= strlen(fragment);
memmove(w, w + strlen(fragment), length);
}
else
{
w++;
length--;
}
}
*w = 0;
printf("%s\n", string);
free(string);
return 0;
}

Related

How can I split a string into a struct?

I want to get a list of all substring separated by "," and put each into a struct.
e.g if i receive "connor,michel" i want to put "connor" in struct[0].name and "michel" in struct[1].name. for now I have this:
struct crit
{
char* titre;
char* noms;
int annees;
float cote;
};
char * les_noms = (char*) malloc(sizeof(char*));
int i = 0;
char *item = strtok(noms, ",");
while(item != NULL)
{
les_noms[i++] = item;
printf("un nom = %s\n", item);
item = strtok(NULL, ",");
}
sorry for the french words.
edit: maked up my mind about les_nom
What about this?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct person
{
char *name;
};
int main()
{
struct person *persons = NULL;
int num_persons = 0;
char names[80] = "joana,cleiton,márcio,elana,joão";
const char sep[2] = ",";
char *item = strtok(names, sep);
while (item != NULL)
{
persons = realloc(persons, ++num_persons * sizeof(struct person));
persons[num_persons - 1].name = malloc(strlen(item)) + 1;
strcpy(persons[num_persons - 1].name, item);
item = strtok(NULL, ",");
}
for (unsigned int i = 0; i < num_persons; i++)
{
printf("%d: %s\n", i, persons[i].name);
}
for (unsigned int i = 0; i < num_persons; i++)
{
free(persons[i].name);
}
free(persons);
}
Or the fixed size solution:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct person
{
char *name;
};
int main()
{
char names[80] = "joana,cleiton,márcio,elana,joão";
const char sep[2] = ",";
unsigned int num_persons = 1;
for (unsigned int i = 0; i < strlen(names); i++)
{
if (names[i] == ',')
{
num_persons++;
}
}
struct person persons[num_persons];
char *item = strtok(names, sep);
for (unsigned int i = 0; item != NULL; i++)
{
persons[i].name = malloc(strlen(item) + 1);
strcpy(persons[i].name, item);
item = strtok(NULL, ",");
}
for (unsigned int i = 0; i < num_persons; i++)
{
printf("%d: %s\n", i, persons[i].name);
}
for (unsigned int i = 0; i < num_persons; i++)
{
free(persons[i].name);
}
}
You probally will need more items in the struct, it is easy, look:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct person
{
char *name;
int len_name;
int id;
};
int main()
{
char names[80] = "joana,cleiton,márcio,elana,joão";
const char sep[2] = ",";
unsigned int num_persons = 1;
for (unsigned int i = 0; i < strlen(names); i++)
{
if (names[i] == ',')
{
num_persons++;
}
}
struct person persons[num_persons];
char *item = strtok(names, sep);
for (unsigned int i = 0; item != NULL; i++)
{
persons[i].name = malloc(strlen(item) + 1);
persons[i].len_name = strlen(item);
persons[i].id = i;
strcpy(persons[i].name, item);
item = strtok(NULL, ",");
}
for (unsigned int i = 0; i < num_persons; i++)
{
printf("%d: %s | %d\n", persons[i].id, persons[i].name, persons[i].len_name);
}
for (unsigned int i = 0; i < num_persons; i++)
{
free(persons[i].name);
}
}

How to check if a string is subset of another string in C

I want to create a function that checks if an array is derived from elements of another array in C. Here is my code. I don't know why it isn't working.
int allDelimiter(char str[81], char delimiters[])
{
int k = 0;
char* pch = strstr(str, delimiters);
if (pch)
{
k++;
}
return k;
}
int main()
{
char string[81] = { ",?',,," };
char delim[] = ", ? ! ''";
int j = 0;
j = allDelimiter(string, delim);
if (j > 0)
{
puts("ALL DELIMITERS");
}
else
{
puts("NOT ALL DELIMITERS");
}
return 0;
}
I want the output to be ALL DELIMITERS i.e all elements of str[] are elements of delim[].
If I understand the question
//returns zero if yes
int containsAll(const char *str, const char *charlist)
{
int result = 0;
while(*str)
{
if(!strchr(charlist, *str++))
{
result = -1;
break;
}
}
return result;
}
int main()
{
char string[81] = { ",?',,," };
char delim[] = ", ? ! ''";
if (!containsAll(string, delim))
{
puts("ALL DELIMITERS");
}
else
{
puts("NOT ALL DELIMITERS");
}
return 0;
}

How to modify a 2d array passed to a function

I know we're able to change a string thanks to a function like this
void c(char *s)
{
int i = 0;
while (s[i])
s[i++] = 's';
}
int main()
{
char str[] = "hello";
c(str);
printf("%s\n", str);
return (0);
}
In this case it will print "sssss".
But how can I modify a 2d array the same way I did for a string ?
I mean without returning the array.
void c(char **s)
{
int i = 0;
int j = 0;
while (s[i])
{
j = 0;
while (s[i][j])
{
s[i][j++] = 's';
}
i++;
}
}
int main()
{
char tab[2][2];
tab[0][0] = 'a';
tab[0][1] = 'b';
tab[1][0] = 'c';
tab[1][1] = 'd';
c(tab);
printf("%c%c\n%c%c", tab[0][0], tab[0][1], tab[1][0], tab[1][1]);
return (0);
}
Here's an idea of how we could do it.
I hope I have been clear enough?
The definition should contain the length. Following will be a good read:
http://www.firmcodes.com/pass-2d-array-parameter-c-2/
void c(char (*s)[length])
#include <stdio.h>
void c(int len, char (*s)[len])
{
int i = 0;
int j = 0;
while (i < len)
{
j = 0;
while (s[i][j])
{
s[i][j++] = 's';
}
i++;
}
}
int main()
{
char tab[2][2];
tab[0][0] = 'a';
tab[0][1] = 'b';
tab[1][0] = 'c';
tab[1][1] = 'd';
c(2, tab);
printf("%c%c\n%c%c", tab[0][0], tab[0][1], tab[1][0], tab[1][1]);
return (0);
}
Sure, its the same. With any dimension count.
void c(char **s, int stringCount)
{
int i = 0, j = 0;
for (j = 0; j < stringCount; ++j)
{
i = 0;
while (s[j][i])
{
s[j][i++] = 's';
}
}
}
int main()
{
char *tab[2] = { "str1", "str2" };
c(tab, 2);
printf("%c%c\n%c%c", tab[0][0], tab[0][1], tab[1][0], tab[1][1]);
printf("%s\n%s", tab[0], tab[1]);
getchar();
return (0);
}

Finding substring in string without using library function

Below is the code template and under /* write your code here */ is my own code.
The template should be correct but there is sth wrong with my code.
My algorithm is to iterate through str until finding the null character.
Then compare each character, if they are the same then iterate through both str and sub, otherwise set continue to iterate through str and reset to the first character of substr.
#include <stdio.h>
int findSubstring(char *str, char *substring);
int main()
{
char str[40], substr[40];
printf("Enter the string: ");
gets(str);
printf("Enter the substring: ");
gets(substr);
printf("findSubstring(): %d\n", findSubstring(str, substr));
return 0;
}
int findSubstring(char *str, char *substr)
{
/* write your code here */
int i = 0, j = 0;
while ((str[j] != '\0')||(substr[i] != '\0')) {
if (substr[i] != str[j]) {
j++;
i = 0;
}
else {
i++;
j++;
}
}
if (substr[i] == '\0')
return 1;
else
return -1;
}
Do not use gets(), which has unavoidable risk of buffer overrun.
The condition of the loop is wrong. The loop should exited if one of *(str + j) or *(substr + i) is a (terminating) null character.
Fixed code:
#include <stdio.h>
int findSubstring(char *str, char *substring);
void safer_gets(char *str, size_t max);
int main(void)
{
char str[40], substr[40];
printf("Enter the string: ");
safer_gets(str, sizeof(str));
printf("Enter the substring: ");
safer_gets(substr, sizeof(str));
printf("findSubstring(): %d\n", findSubstring(str, substr));
return 0;
}
int findSubstring(char *str, char *substr)
{
int i = 0, j = 0;
while ((*(str + j) != '\0')&&(*(substr + i) != '\0')) {
if (*(substr + i) != *(str + j)) {
j++;
i = 0;
}
else {
i++;
j++;
}
}
if (*(substr + i) == '\0')
return 1;
else
return -1;
}
void safer_gets(char *str, size_t max)
{
int i;
fgets(str, max, stdin);
for (i = 0; *(str + i) != '\0'; i++) {
if (*(str + i) == '\n') {
*(str + i) = '\0';
break;
}
}
}
/*--------------------------One more simple example-----------------------------
Find the words from a set of words containing a given substring?
Input: Set of Words: [blackcat, blackdog, blackrat, whitetiger, blueelephant],
Substring: black
Output:[blackcat, blackdog, blackrat]
-----------------------------------------------------------------------------------------*/
#include <iostream>
#include <cstring>
int substring(char* sub,char* string);
int main()
{
const char* Names[] { "blackcat", "blackdog", "blackrat", "whitetiger", "blueelephant" };
char substr[]{ "black" };
int found{ -1 };
for (auto strings: Names)
{
found = substring(substr, const_cast<char*>(strings));
if (found != -1) {
std::cout << strings << " ";
}
}
std::cout << std::endl;
return 0;
}
int substring(char* sub, char* string)
{
int i{};
int j{};
while ((string[i] != '\0') && (sub[j] != '\0'))
{
if (string[i] != sub[j]) {
j++;
i = 0;
}
else {
i++;
j++;
}
}
if (sub[j] == '\0' && i != 0) {
return 1;
}
else {
return -1;
}
}
#include<stdio.h>
#include<conio.h>
void main()
{
char s[100],sub[50];
int i,j,c=0;
clrscr();
printf("enter string and substring\n");
gets(s);
printf("\n");
gets(sub);
printf("\n");
i=0;
j=0;
while(s[i]!='\0')
{
if(s[i]!=sub[j])
i++;
else if(s[i]==sub[j])
{
while(sub[j]!='\0')
{
if(s[i]==sub[j])
{
i++;
j++;
c++;
}
else
{
c=0;
break;
}
}
}
}
if(c!=0)
printf("\nsubstring is present \n ");
else
printf("\nsubstring is absent \n ");
getch();
}

how to implement next() PHP function in C

I am tried to implement next() PHP function in C. if I have
The different to my implementation is I want to do this work with more one points. For example:
if I have two char * like:
char * a = "ac\0";
char * b = "bd\0";
and I call:
printf("%c", cgetnext(a));
printf("%c", cgetnext(b));
printf("%c", cgetnext(a));
printf("%c", cgetnext(b));
gets an output like: abcd
but I get abab
here is my code:
`#include <string.h>
#include <stdlib.h>
typedef struct
{
int pLocation;
int myindex;
int lastIndex;
} POINTERINFORMATION;
int __myIndex = 0;
int pointersLocationsLength = 0;
char * temparr = NULL;
POINTERINFORMATION pointersLocations[256];
int
plAdd (int p)
{
if (pointersLocationsLength >= sizeof(pointersLocations)) {
return -1;
} else {
pointersLocations[pointersLocationsLength].pLocation = p;
pointersLocations[pointersLocationsLength].lastIndex = 0;
pointersLocationsLength ++;
return pointersLocationsLength;
}
}
int
getPointer (int p, POINTERINFORMATION * out)
{
int i;
for (i = 0; i < pointersLocationsLength; i++)
{
if(pointersLocations[pointersLocationsLength].pLocation == p)
{
pointersLocations[i].myindex = i;
*out = pointersLocations[i];
return 1;
}
}
return 0;
}
void
getPointerIndex(char ** variable, int * val)
{
char * buf = malloc(256);
if(sprintf(buf,"%p", &variable) > 0){
*val = strtol(buf, NULL, 16 );
} else {
*val = -1;
}
}
int
inArrayOfPointers (int pointer)
{
POINTERINFORMATION pi;
return getPointer(pointer, &pi);
}
char
cgetnext(char * arr)
{
char * myarr;
const size_t size = sizeof(char *) + 1;
int pof;
myarr = malloc(size);
getPointerIndex (&arr, &pof);
if (inArrayOfPointers(pof)){
POINTERINFORMATION pi;
if (getPointer(pof, &pi))
{
myarr = (char *)*(int *)pi.pLocation;
__myIndex = pi.lastIndex;
++pointersLocations[pi.myindex].myindex;
} else {
return 0;
}
} else {
if (plAdd(pof) == -1) {
printf(" CANNOT ADD ELEMENT TO ARRAY\n");
exit(0);
} else {
myarr = arr;
__myIndex = 0;
}
}
if (strlen(myarr) == __myIndex) {
return 0;
} else {
temparr = malloc(size);
temparr = strdup(myarr);
return myarr[__myIndex];
}
}`
how to fix this? differents solutions for solve it are very apreciated! Thanks in advance.
If you are specifically interested in char* "arrays", then a simple solution might be to just increment the pointer. Note that if using dynamically allocated memory, you need to save the original pointer to free it. The same idea could be used for other data types as well.
This is an example of what I mean. cgetnext here just returns the character at the current position in the array and increments pointer (that is passed by address).
char cgetnext( char **p )
{
assert( p != NULL );
// check for end of string
if ( **p == '\0' )
return '\0';
return *(*p)++;
}
int main( int argc, char* argv[] )
{
char *a = "ac";
char *b = "bd";
printf( "%c", cgetnext(&a));
printf( "%c", cgetnext(&b));
printf( "%c", cgetnext(&a));
printf( "%c", cgetnext(&b));
}

Resources