I need help with a couple of things:
I'm trying to delete a word from a pointer and put it in a new pointer with a new length but i am not able to copy it to the new pointer
I'm not sure when should I use the free() function.
when I use the free(str) in the delete function it crashes.
After I copy the "str" to the "newStr" what is the best way to copy the "newStr" back to the "str" with the new length?
Please help me understand it, I'm new with this and I googled it, I tried looking here and didn't find something that could help me.
void delete(char *str)
{
int i, indexStart = 0, indexEnd = 0, wordlen = 0, newLen = 0, len = 0;
printf("Enter the index of the word that you want to remove: ");
scanf("%d", &i);
indexs(i, str,&indexStart,&indexEnd,&wordlen);
len = strlen(str);
newLen = len - wordlen - 1;
char *newStr = (char*)malloc(newLen * sizeof(char));
if (newStr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
for (int j = 0; j < len; j++)
{
if (j< (indexStart - 1) || j > indexEnd)
{
*newStr = *str;
newStr++;
}
str++;
}
free(str);
//free(newStr);
printf("The new string: %s\n", newStr);
}
void main()
{
char *str = (char*)malloc(1 * sizeof(char));
if (str == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
text(str);
if (str != NULL)
{
delete(str);
}
free(str);
system("pause");
}
According to the structured programming paradigm your functions should solve small separate tasks. But your function delete() prints to the console, scans input, allocates new string and fills this new string. But what's event worse is the call exit() in this function. If something went wrong, function must to return an error, but not to stop the program. Also names of functions should relfect what they do.
Use free() for every memory block allocated by malloc().
So, this is a working code:
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
const char *findWord(const char *str, const char *delimiters, unsigned index) {
// validate input parameters
if (!str || !delimiters) {
return NULL;
}
// count words
unsigned count = 0;
while (*str && count < index) {
// skip delimiters
while (*str && !strchr(delimiters, *str)) {
str++;
}
if (*str) {
count++;
}
// skip word
while (*str && strchr(delimiters, *str)) {
str++;
}
}
// if index is too big returns NULL
return *str ? str : NULL;
}
unsigned countLengthOfWord(const char *str, const char *delimiters) {
// validate input parameters
if (!str || !delimiters) {
return 0;
}
// count length
unsigned length = 0;
while (*str && !strchr(delimiters, *str++)) {
length++;
}
return length;
}
char *cutWord(char *str, const char *delimiters, unsigned index) {
// validate input parameters
if (!str) {
return NULL;
}
str = (char *)findWord(str, delimiters, index);
// if index is too big, return NULL
if (!str) {
return NULL;
}
// allocate new string for word
unsigned length = countLengthOfWord(str, delimiters);
char *word = malloc(length + 1);
// check if allocation was successfull
if (!word) {
return NULL;
}
// copy word
strncpy(word, str, length);
word[length] = '\0';
// cut word from string
const char *ptr = str + length;
while (*ptr) {
*str++ = *ptr++;
}
*str = '\0';
return word;
}
int main() {
char str1[] = "Hello, my world!";
char str2[] = "Hello, my world!";
char str3[] = "Hello, my world!";
char *word1 = cutWord(str1, " ,!", 0);
char *word2 = cutWord(str2, " ,!", 1);
char *word3 = cutWord(str3, " ,!", 2);
if (word1) {
printf("word: %s\nstring: %s\n\n", word1, str1);
}
if (word2) {
printf("word: %s\nstring: %s\n\n", word2, str2);
}
if (word3) {
printf("word: %s\nstring: %s\n\n", word3, str3);
}
// release allocated memory
free(word1);
free(word2);
free(word3);
getchar();
return 0;
}
Related
I have a variable length string that I am trying to divide from plus signs and study on:
char string[] = "var1+vari2+varia3";
for (int i = 0; i != sizeof(string); i++) {
memcpy(buf, string[0], 4);
buf[9] = '\0';
}
since variables are different in size I am trying to write something that is going to take string into loop and extract (divide) variables. Any suggestions ? I am expecting result such as:
var1
vari2
varia3
You can use strtok() to break the string by delimiter
char string[]="var1+vari2+varia3";
const char delim[] = "+";
char *token;
/* get the first token */
token = strtok(string, delim);
/* walk through other tokens */
while( token != NULL ) {
printf( " %s\n", token );
token = strtok(NULL, delim);
}
More info about the strtok() here: https://man7.org/linux/man-pages/man3/strtok.3.html
It seems to me that you don't just want to want to print the individual strings but want to save the individual strings in some buffer.
Since you can't know the number of strings nor the length of the individual string, you should allocate memory dynamic, i.e. use functions like realloc, calloc and malloc.
It can be implemented in several ways. Below is one example. To keep the example simple, it's not performance optimized in anyway.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
char** split_string(const char* string, const char* token, int* num)
{
assert(string != NULL);
assert(token != NULL);
assert(num != NULL);
assert(strlen(token) != 0);
char** data = NULL;
int num_strings = 0;
while(*string)
{
// Allocate memory for one more string pointer
char** ptemp = realloc(data, (num_strings + 1) * sizeof *data);
if (ptemp == NULL) exit(1);
data = ptemp;
// Look for token
char* tmp = strstr(string, token);
if (tmp == NULL)
{
// Last string
// Allocate memory for one more string and copy it
int len = strlen(string);
data[num_strings] = calloc(len + 1, 1);
if (data[num_strings] == NULL) exit(1);
memcpy(data[num_strings], string, len);
++num_strings;
break;
}
// Allocate memory for one more string and copy it
int len = tmp - string;
data[num_strings] = calloc(len + 1, 1);
if (data[num_strings] == NULL) exit(1);
memcpy(data[num_strings], string, len);
// Prepare to search for next string
++num_strings;
string = tmp + strlen(token);
}
*num = num_strings;
return data;
}
int main()
{
char string[]="var1+vari2+varia3";
// Split the string into dynamic allocated memory
int num_strings;
char** data = split_string(string, "+", &num_strings);
// Now data can be used as an array-of-strings
// Example: Print the strings
printf("Found %d strings:\n", num_strings);
for(int i = 0; i < num_strings; ++i) printf("%s\n", data[i]);
// Free the memory
for(int i = 0; i < num_strings; ++i) free(data[i]);
free(data);
}
Output
Found 3 strings:
var1
vari2
varia3
You can use a simple loop scanning the string for + signs:
char string[] = "var1+vari2+varia3";
char buf[sizeof(string)];
int start = 0;
for (int i = 0;;) {
if (string[i] == '+' || string[i] == '\0') {
memcpy(buf, string + start, i - start);
buf[i - start] = '\0';
// buf contains the substring, use it as a C string
printf("%s\n", buf);
if (string[i] == '\0')
break;
start = ++i;
} else {
i++;
}
}
Your code does not have any sense.
I wrote such a function for you. Analyse it as sometimes is good to have some code as a base
char *substr(const char *str, char *buff, const size_t start, const size_t len)
{
size_t srcLen;
char *result = buff;
if(str && buff)
{
if(*str)
{
srcLen = strlen(str);
if(srcLen < start + len)
{
if(start < srcLen) strcpy(buff, str + start);
else buff[0] = 0;
}
else
{
memcpy(buff, str + start, len);
buff[len] = 0;
}
}
else
{
buff[0] = 0;
}
}
return result;
}
https://godbolt.org/z/GjMEqx
I am in the stage of preparing myself for exams, and the thing that I m least proud of are my skills with strings. What I need to do is remove a word from a sentence, without using <string.h> library at all.
This is what I've got so far. It keeps showing me that certain variables are not declared, such as start and end.
#include <stdio.h>
/* Side function to count the number of letters of the word we wish to remove */
int count(char *s) {
int counter = 0;
while (*s++) {
counter++;
s--;
return counter;
}
/* Function to remove a word from a sentence */
char *remove_word(const char *s1, const char *s2) {
int counter2 = 0;
/* We must remember where the string started */
const char *toReturn = s1;
/* Trigger for removing the word */
int found = 1;
/* First we need to find the word we wish to remove [Don't want to
use string.h library for anything associated with the task */
while (*s1 != '\0') {
const char *p = s1;
const char *q = s2;
if (*p == *q)
const char *start = p;
while (*p++ == *q++) {
counter2++;
if (*q != '\0' && counter2 < count(s2))
found = 0;
else {
const char *end = q;
}
}
/* Rewriting the end of a sentence to the beginning of the found word */
if (found) {
while (*start++ = *end++)
;
}
s1++;
}
return toReturn;
}
void insert(char niz[], int size) {
char character = getchar();
if (character == '\n')
character = getchar();
int i = 0;
while (i < size - 1 && character != '\n') {
array[i] = character;
i++;
character = getchar();
}
array[i] = '\0';
}
int main() {
char stringFirst[100];
char stringSecond[20];
printf("Type your text here: [NOT MORE THAN 100 CHARACTERS]\n");
insert(stringFirst, 100);
printf("\nInsert the word you wish to remove from your text.");
insert(stringSecond, 20);
printf("\nAfter removing the word, the text looks like this now: %s", stringFirst);
return 0;
}
your code is badly formed, i strongly suggest compiling with:
gcc -ansi -Wall -pedantic -Werror -D_DEBUG -g (or similar)
start with declaring your variables at the beginning of the function block, they are known only inside the block they are declared in.
your count function is buggy, missing a closing '}' (it doesn't compile)
should be something like
size_t Strlen(const char *s)
{
size_t size = 0;
for (; *s != '\n'; ++s, ++size)
{}
return size;
}
implementing memmove is much more efficient then copy char by char
I reformatted you code for small indentation problems and indeed indentation problems indicate real issues:
There is a missing } in count. It should read:
/* Side function to count the number of letters of the word we wish to remove */
int count(char *s) {
int counter = 0;
while (*s++) {
counter++;
}
return counter;
}
or better:
/* Side function to count the number of letters of the word we wish to remove */
int count(const char *s) {
const char *s0 = s;
while (*s++) {
continue;
}
return s - s0;
}
This function counts the number of bytes in the string, an almost exact clone of strlen except for the return type int instead of size_t. Note also that you do not actually use nor need this function.
Your function insert does not handle EOF gracefully and refuses an empty line. Why not read a line with fgets() and strip the newline manually:
char *input(char buf[], size_t size) {
size_t i;
if (!fgets(buf, size, stdin))
return NULL;
for (i = 0; buf[i]; i++) {
if (buf[i] == '\n') {
buf[i] = '\0';
break;
}
}
return buf;
}
In function remove_word, you should define start and end with a larger scope, typically the outer while loop's body. Furthermore s1 should have type char *, not const char *, as the phrase will be modified in place.
You should only increment p and q if the test succeeds and you should check that p and q are not both at the end of their strings.
last but not least: you do not call remove_word in the main function.
The complete code can be simplified into this:
#include <stdio.h>
/* Function to remove a word from a sentence */
char *remove_word(char *s1, const char *s2) {
if (*s2 != '\0') {
char *dst, *src, *p;
const char *q;
dst = src = s1;
while (*src != '\0') {
for (p = src, q = s2; *q != '\0' && *p == *q; p++, q++)
continue;
if (*q == '\0') {
src = p; /* the word was found, skip it */
} else {
*dst++ = *src++; /* otherwise, copy this character */
}
}
*dst = '\0'; /* put the null terminator if the string was shortened */
}
return s1;
}
char *input(char buf[], size_t size) {
size_t i;
if (!fgets(buf, size, stdin))
return NULL;
for (i = 0; buf[i]; i++) {
if (buf[i] == '\n') {
buf[i] = '\0';
break;
}
}
return buf;
}
int main() {
char stringFirst[102];
char stringSecond[22];
printf("Type your text here, up to 100 characters:\n");
if (!input(stringFirst, sizeof stringFirst))
return 1;
printf("\nInsert the word you wish to remove from your text: ");
if (!input(stringSecond, sizeof stringSecond))
return 1;
printf("\nAfter removing the word, the text looks like this now: %s\n",
remove_word(stringFirst, stringSecond));
return 0;
}
Your start and end pointers are defined within a block which makes their scope limited within that block. So, they are not visible to other parts of your code, and if you attempt to reference them outside their scope, the compiler will complain and throw an error. You should declare them at the beginning of the function block.
That said, consider the following approach to delete a word from a string:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int delete_word(char *buf,
const char *word);
int main(void)
{
const char word_to_delete[] = "boy";
fputs("Enter string: ", stdout);
char buf[256];
fgets(buf, sizeof(buf), stdin);
if (delete_word(buf, word_to_delete))
{
printf("Word %s deleted from buf: ", word_to_delete);
puts(buf);
}
else
{
printf("Word %s not found in buf: ", word_to_delete);
puts(buf);
}
system("PAUSE");
return 0;
}
int chDelimit(int ch)
{
return
(ch == '\n' || ch == '\t') ||
(ch >= ' ' && ch <= '/') ||
(ch >= ':' && ch <= '#') ||
(ch >= '[' && ch <= '`') ||
(ch >= '{' && ch <= '~') ||
(ch == '\0');
}
char *find_pattern(char *buf,
const char *pattern)
{
size_t n = 0;
while (*buf)
{
while (buf[n] && pattern[n])
{
if (buf[n] != pattern[n])
{
break;
}
n++;
}
if (!pattern[n])
{
return buf;
}
else if (!*buf)
{
return NULL;
}
n = 0;
buf++;
}
return NULL;
}
char *find_word(char *buf,
const char *word)
{
char *ptr;
size_t wlen;
wlen = strlen(word);
ptr = find_pattern(buf, word);
if (!ptr)
{
return NULL;
}
else if (ptr == buf)
{
if (chDelimit(buf[wlen]))
{
return ptr;
}
}
else
{
if (chDelimit(ptr[-1]) &&
chDelimit(ptr[wlen]))
{
return ptr;
}
}
ptr += wlen;
ptr = find_pattern(ptr, word);
while (ptr)
{
if (chDelimit(ptr[-1]) &&
chDelimit(ptr[wlen]))
{
return ptr;
}
ptr += wlen;
ptr = find_pattern(ptr, word);
}
return NULL;
}
int delete_word(char *buf,
const char *word)
{
size_t n;
size_t wlen;
char *tmp;
char *ptr;
wlen = strlen(word);
ptr = find_word(buf, word);
if (!ptr)
{
return 0;
}
else
{
n = ptr - buf;
tmp = ptr + wlen;
}
ptr = find_word(tmp, word);
while (ptr)
{
while (tmp < ptr)
{
buf[n++] = *tmp++;
}
tmp = ptr + wlen;
ptr = find_word(tmp, word);
}
strcpy(buf + n, tmp);
return 1;
}
If you have to do it manually, just loop over the indicies of your string to find the first one that matches and than you’ll have a second loop that loops for all the others that matches and resets all and jumps to the next index of the first loop if not matched something in order to continue the searching. If I recall accuretaly, all strings in C are accesible just like arrays, you’ll have to figure it out how. Don’t afraid, those principles are easy! C is an easy langugae, thiught very long to write.
In order to remove: store the first part in an array, store the second part in an array, alloc a new space for both of them and concatinate them there.
Thanks, hit the upvote button.
Vitali
EDIT: use \0 to terminate your newly created string.
char* my_strtok (char* s1,const char* s2){
char *res = NULL;
size_t i, j, len1 = mstrlen(s1), len2 = mstrlen(s2);
for(i=0U; i< len1; i++) {
for(j=0U; j<len2; j++) {
if(s1[i] == s2[j]) {
s1[i] = '\0'; res = (s1 + i+ 1);
break;
}
}
}
return res;
}
can you say it is the right realization of strtok?
Or you can show your realization?
You need to have a place where you keep the current position of the input-pointer. Example using strspn() and strcspn() as the means to get the positions of the delimiters:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// SOME CHECKS OMMITTED!
// helper for testing, not necessary for strtok()
static char *strduplicator(const char *s)
{
char *dup;
dup = malloc(strlen(s) + 1);
if (dup != NULL) {
strcpy(dup, s);
}
return dup;
}
// thread-safe (sort of) version
char *my_strtok(char *in, const char *delim, char **pos)
{
char *token = NULL;
// if the input is NULL, we assume that this
// function run already and use the new position
// at "pos" instead
if (in == NULL) {
in = *pos;
}
// skip leading delimiter that are left
// there from the last run, if any
in += strspn(in, delim);
// if it is still not the end of the input
if (*in != '\0') {
// start of token is at the current position, set it
token = in;
// skip non-delimiters, that is: find end of token
in += strcspn(in, delim);
// strip of token by setting first delimiter to NUL
// that is: set end of token
if (*in != '\0') {
*in = '\0';
in++;
}
}
// keep current position of input in "pos"
*pos = in;
return token;
}
int main(void)
{
char *in_1 = strduplicator("this,is;the:test-for!strtok.");
char *in_2 = strduplicator("this,is;the:test-for!my_strtok.");
char *position, *token, *s_in1 = in_1, *s_in2 = in_2;
const char *delimiters = ",;.:-!";
token = strtok(in_1, delimiters);
printf("BUILDIN: %s\n", token);
for (;;) {
token = strtok(NULL, delimiters);
if (token == NULL) {
break;
}
printf("BUILDIN: %s\n", token);
}
token = my_strtok(in_2, delimiters, &position);
printf("OWNBUILD: %s\n", token);
for (;;) {
token = my_strtok(NULL, delimiters, &position);
if (token == NULL) {
break;
}
printf("OWNBUILD: %s\n", token);
}
free(s_in1);
free(s_in2);
exit(EXIT_SUCCESS);
}
If you want to have the ordinary char *strtok(char *str, const char *delim); you can do e.g.:
static char *pos;
char *own_strtok(char *in, const char *delim)
{
return my_strtok(in, delim, &pos);
}
The functions str[c]spn() are quite simple. To quote the man-page of strspn()
The strspn() function returns the number of bytes in the initial segment of s which consist only of bytes from accept.
size_t my_strspn(const char *s, const char *accept)
{
const char *delim;
size_t size = 0;
// step through the input
while (*s != '\0') {
// step through delimiters and test
for (delim = accept; *delim != '\0'; delim++) {
if (*s == *delim) {
break;
}
}
// we are through all of the delimiters without success,
// terminate
if (*delim == '\0') {
break;
} else {
size++;
}
s++;
}
return size;
}
The inverse function strcspn() is even simpler. To, again, quote from the man-page:
The strcspn() function returns the number of bytes in the initial segment of s which are not in the string reject.
size_t my_strcspn(const char *s, const char *reject)
{
const char *delim;
size_t size = 0;
// step through the input
while (*s != '\0') {
// step through delimiters and test
for (delim = reject; *delim != '\0'; delim++) {
if (*s == *delim) {
return size;
}
}
size++;
s++;
}
return size;
}
With n the size of the input and k the size of the set of delimiters the time complexity is O(kn). In theory the size of k cannot exceed the size of the alphabet of the input and we should be able to assume k << n. But that assumes that the string containing the delimiters is unique. That is not always the case.
strtok(
"This is a sentence without the last letter of the alphabet.",
"zzz/* 1,000,000,000 other z's omitted */zzz"
);
So be careful with auto-generated delimiter sets and add an extra check if that danger is real (e.g.: with user input).
I want to implement a c code such that it replaces only the exact matching not part of another string.
check out my code.
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="This is a simpled simple string";
char * pch;
char str1[]= "simple";
pch = strstr (str,str1);
strncpy (pch,"sample",6);
puts (str);
return 0;
}
the above code gives the output : This is sampled simple string
I want the output to be : This is simpled sample string
please help
Thanks.
The best way to deal with these types of question is consider each and every word one-by-one. And then check whether, the pattern (which we are looking for?) is present in the given string or not, if yes then replace it with replacing word.
Below is my code. (I know it may seem bit odd one out, but trust me it will work for any pattern-matching and replacement problem). It will reduce and expand the final output according to the given pattern word and its corresponding replacement word.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
/* This program will replace the "demo" with "program" */
char input[] = " isdemo Hello this is demo. replace demo with demoes something else demo";
char pattern[] = "demo";
char replace[] = "program";
char output[105];
int index = 0;
/*Read the the input line word-by-word,
if the word == pattern[], then replace it else do nothing */
for(int i=0; i<strlen(input);) {
while(i<strlen(input) && !isalpha(input[i])) {
output[index++] = input[i++];
}
char temp[105]; int j = 0;
while(i<strlen(input) && isalpha(input[i])) {
temp[j++] = input[i++];
}
temp[j] = 0;
if(strcmp(temp, pattern) == 0) {
strncpy(output+index, replace, strlen(replace));
index += strlen(replace);
} else {
strncpy(output+index, temp, strlen(temp));
index += strlen(temp);
}
}
output[index] = 0;
puts(output);
return 0;
}
If i'm still missing any test case. I will be pleased to know about it.
First, you need search the entire string continuously until no substring is found, second, you need check the char before and after the substring returned by strstr, to make sure that the found substring is a complete word. When check for word boundary, take special care when the word is at the beginning or end of the longer string. For example:
#include <stdio.h>
#include <string.h>
int main(void)
{
char str[] ="simple simples is a simpled simple string simple";
char *s = str;
char *pch = str;
char str1[]= "simple";
int len = strlen(str1);
int pos;
while (1) {
pch = strstr(s, str1);
if (!pch) // no more occurrences of str1, quit
break;
pos = pch - str;
if (pos == 0) { // if it's the beginning
if (!isalpha(pch[len])) {
strncpy(pch, "sample", 6);
}
} else { // check two ends
if (!isalpha(*(pch-1)) && !isalpha(*(pch+len))) {
strncpy(pch, "sample", 6);
}
}
s = pch + len;
}
puts(str);
return 0;
}
I updated my code.This deals with the replacement that you want.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void replace(char *buf, size_t bufSize, const char *word_to_replace, const char *replacement_word);
int main(void)
{
char str[100] = "simple Asimple simpleB This is a simpled simple string and simple is good sometimes!, simple";
replace(str, sizeof(str), "simple", "sample");
printf("%s\n", str);
return 0;
}
void replace(char *buf, size_t bufSize, const char *word_to_replace, const char *replacement_word)
{
size_t buf_len = strlen(buf), word_len = strlen(word_to_replace);
char *ptr = strstr(buf, word_to_replace);
if (ptr == NULL) {
fprintf(stderr, "Could not find matches.\n");
return;
}
bool _G = 0;
char *tmp = (char *)malloc(bufSize);
// Deal with begining of line
if (ptr == buf) {
if (ptr[word_len] == ' ' || ptr[word_len] == '\0') {
_G = 1;
}
if (_G) {
strcpy_s(tmp, bufSize, ptr + word_len);
*ptr = 0;
strcat_s(buf, bufSize, replacement_word);
strcat_s(buf, bufSize, tmp);
_G = 0;
}
}
else {
if (*(ptr - 1) == ' ' && (ptr[word_len] == ' ' || ptr[word_len] == '\0')) {
_G = 1;
}
if (_G) {
strcpy_s(tmp, bufSize, ptr + word_len);
*ptr = 0;
strcat_s(buf, bufSize, replacement_word);
strcat_s(buf, bufSize, tmp);
_G = 0;
}
}
// deal with the rest
while (ptr = strstr(ptr + 1, word_to_replace))
{
if (*(ptr - 1) == ' ' && (ptr[word_len] == ' ' || ptr[word_len] == '\0')) {
_G = 1;
}
if (_G) {
strcpy_s(tmp, bufSize, ptr + word_len);
*ptr = 0;
strcat_s(buf, bufSize, replacement_word);
strcat_s(buf, bufSize, tmp);
_G = 0;
}
}
free(tmp);
}
A word can start with space or may lie at the start of string and can end with a space, a full stop, a comma or with the end of string. using these conditions you can easily identify any word within a string. Following code describes it according to your example.
Using this code you can replace a word with another word of any size.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int main()
{
char str[] = "simple This is a simpled simple simple. simple, string simple";
char * pch;
char * result = str;
char * temp;
char str1[] = "simple"; //string to be replaced
char str2[] = "sample"; //string to be replaced with
pch = strstr(result, str1);
while(pch)
{
temp = result;
if ((pch == str || *(pch - 1) == ' ') && (strlen(pch) == strlen(str1) || !isalpha(*(pch + strlen(str1)))))
{
result = (char*)malloc(strlen(temp)+(strlen(str2) - strlen(str1))+1); //allocate new memory, +1 for trailing null character
strncpy(result, temp, pch - temp); // copy previous string till found word to new allocated memory
strncpy(result + (pch - temp), str2, strlen(str2)); // replace previous word with new word
strncpy(result + (pch - temp) + strlen(str2), pch + strlen(str1), strlen(pch + strlen(str1))); // place previous string after replaced word
strncpy(result + strlen(temp) + (strlen(str2) - strlen(str1)), "\0", 1); // place null character at the end of string
if (temp != str)
free(temp); // free extra memory
}
pch = strstr(result + (pch - temp) + 1, str1); // search for another word in new string after the last word was replaced
}
puts(result);
if (result != str)
free(result);
return 0;
}
I'm new to C programming. I have a task to do.
User inputs two strings. What I need to do is to create a new string that will consist only from common letters of those two given strings.
For example:
if given:
str1 = "ABCDZ"
str2 = "ADXYZ"
the new string will look like: "ADZ".
I can't make it work. I think there must be a better (more simple) algorithm but I have waisted too much time for this one so I want to complete it .. need your help!
what I've done so far is this:
char* commonChars (char* str1, char* str2)
{
char *ptr, *qtr, *arr, *tmp, *ch1, *ch2;
int counter = 1;
ch1 = str1;
ch2 = str2;
arr = (char*) malloc ((strlen(str1)+strlen(str2)+1)*(sizeof(char))); //creating dynamic array
strcpy(arr, str1);
strcat(arr,str2);
for (ptr = arr; ptr < arr + strlen(arr); ptr++)
{
for (qtr = arr; qtr < arr + strlen(arr); qtr++) // count for each char how many times is appears
{
if (*qtr == *ptr && qtr != ptr)
{
counter++;
tmp = qtr;
}
}
if (counter > 1)
{
for (qtr = tmp; *qtr; qtr++) //removing duplicate characters
*(qtr) = *(qtr+1);
}
counter = 1;
}
sortArray(arr, strlen(arr)); // sorting the string in alphabetical order
qtr = arr;
for (ptr = arr; ptr < arr + strlen(arr); ptr++, ch1++, ch2++) //checking if a letter appears in both strings and if at least one of them doesn't contain this letter - remove it
{
for (qtr = ptr; *qtr; qtr++)
{
if (*qtr != *ch1 || *qtr != *ch2)
*qtr = *(qtr+1);
}
}
}
Don't know how to finish this code .. i would be thankful for any suggestion!
The output array cannot be longer that the shorter of the two input arrays.
You can use strchr().
char * common (const char *in1, const char *in2) {
char *out;
char *p;
if (strlen(in2) < strlen(in1)) {
const char *t = in2;
in2 = in1;
in1 = t;
}
out = malloc(strlen(in2)+1);
p = out;
while (*in1) {
if (strchr(in2, *in1)) *p++ = *in1;
++in1;
}
*p = '\0';
return out;
}
This has O(NxM) performance, where N and M are the lengths of the input strings. Because your input is alphabetical and unique, you can achieve O(N+M) worst case performance. You apply something that resembles a merge loop.
char * common_linear (const char *in1, const char *in2) {
char *out;
char *p;
if (strlen(in2) < strlen(in1)) {
const char *t = in2;
in2 = in1;
in1 = t;
}
out = malloc(strlen(in2)+1);
p = out;
while (*in1 && *in2) {
if (*in1 < *in2) {
++in1;
continue;
}
if (*in2 < *in1) {
++in2;
continue;
}
*p++ = *in1;
++in1;
++in2;
}
*p = '\0';
return out;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define min(x,y) ((x)<(y)? (x) : (y))
char* commonChars (const char *str1, const char *str2){
//str1, str2 : sorted(asc) and unique
char *ret, *p;
int len1, len2;
len1=strlen(str1);
len2=strlen(str2);
ret = p = malloc((min(len1, len2)+1)*sizeof(char));
while(*str1 && *str2){
if(*str1 < *str2){
++str1;
continue;
}
if(*str1 > *str2){
++str2;
continue;
}
*p++ = *str1++;
++str2;
}
*p ='\0';
return ret;
}
char *deleteChars(const char *str, const char *dellist){
//str, dellist : sorted(asc) and unique
char *ret, *p;
ret = p = malloc((strlen(str)+1)*sizeof(char));
while(*str && *dellist){
if(*str < *dellist){
*p++=*str++;
continue;
}
if(*str > *dellist){
++dellist;
continue;
}
++str;
++dellist;
}
if(!*dellist)
while(*str)
*p++=*str++;
*p ='\0';
return ret;
}
int main(void){
const char *str1 = "ABCDXYZ";
const char *str2 = "ABCDZ";
const char *str3 = "ADXYZ";
char *common2and3;
char *withoutcommon;
common2and3 = commonChars(str2, str3);
//printf("%s\n", common2and3);//ADZ
withoutcommon = deleteChars(str1, common2and3);
printf("%s\n", withoutcommon);//BCXY
free(common2and3);
free(withoutcommon);
return 0;
}
I will do something like this :
char* commonChars(char* str1, char* str2) {
char* ret = malloc(strlen(str1) * sizeof(char));
int i = j = k = 0;
for (; str1[i] != '\n'; i++, j++) {
if (str1[i] == str2[j]) {
ret[k] = str1[i];
k++;
}
}
ret[k] = '\0';
ret = realloc(ret, k);
return ret;
}
It's been a while i didn't do C, hope this is correct
You can use strpbrk() function, to do this job cleanly.
const char * strpbrk ( const char * str1, const char * str2 );
char * strpbrk ( char * str1, const char * str2 );
Locate characters in string
Returns a pointer to the first occurrence in str1 of any of the characters that are part of str2, or a null pointer if there are no matches.
The search does not include the terminating null-characters of either strings, but ends there.
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "ABCDZ";
char key[] = "ADXYZ";
char *newString = malloc(sizeof(str)+sizeof(key));
memset(newString, 0x00, sizeof(newString));
char * pch;
pch = strpbrk (str, key);
int i=0;
while (pch != NULL)
{
*(newString+i) = *pch;
pch = strpbrk (pch+1,key);
i++;
}
printf ("%s", newString);
return 0;
}
Sorry for the weird use of char arrays, was just trying to get it done fast. The idea behind the algorithm should be obvious, you can modify some of the types, loop ending conditions, remove the C++ elements, etc for your purposes. It's the idea behind the code that's important.
#include <queue>
#include <string>
#include <iostream>
using namespace std;
bool isCharPresent(char* str, char c) {
do {
if(c == *str) return true;
} while(*(str++));
return false;
}
int main ()
{
char str1[] = {'h', 'i', 't', 'h', 'e', 'r', 'e', '\0'};
char str2[] = {'a', 'h', 'i', '\0'};
string result = "";
char* charIt = &str1[0];
do {
if(isCharPresent(str2, *charIt))
result += *charIt;
} while(*(charIt++));
cout << result << endl; //hih is the result. Minor modifications if dupes are bad.
}
So i found the solution for my problem. Eventually I used another algorithm which, as turned out, is very similar to what #BLUEPIXY and #user315052 have suggested. Thanks everyone who tried to help! Very nice and useful web source!
Here is my code. Someone who'll find it useful can use it.
Note:
(1) str1 & str2 should be sorted alphabetically;
(2) each character should appear only once in each given strings;
char* commonChars (char* str1, char* str2)
{
char *ptr, *arr,*ch1, *ch2;
int counter = 0;
for (ch1 = str1; *ch1; ch1++)
{
for(ch2 = str2; *ch2; ch2++)
{
if (*ch1 == *ch2)
counter++;
}
}
arr = (char*)malloc ((counter+1) * sizeof(char));
ch1 = str1;
ch2 = str2;
ptr = arr;
for (ch1 = str1; *ch1; ch1++,ch2++)
{
while (*ch1 < *ch2)
{
ch1++;
}
while (*ch1 > *ch2)
{
ch2++;
}
if (*ch1 == *ch2)
{
*ptr = *ch1;
ptr++;
}
}
if (ptr = arr + counter)
*ptr = '\0';
return arr;
}