Reputation: 2604
I need to change the text in array in a way, that everywhere I have a
character, I need to change it to123
.
Example: for the given text: ayasxka
I should got this: 12123k123
or this 12323k123
text.
I almost got it to work, but instead of k
between numbers, I got s
, I mean, this is my result: 12123s123
.
int main()
{
int i, j = 0;
char t[] = "ayasxka";
char *r = malloc(sizeof(char) * (strlen(t) + 2));
memset(r, '\0', (strlen(t) + 1));
for(i=0; t[i] != '\0'; i++)
{
if(t[i] == 'a')
{
r[i] = '1';
r[i+1] = '2';
r[i+2] = '3';
}
else
r[i+2] = t[i];
}
printf("%s\n", r);
free(r);
return 0;
}
Upvotes: 0
Views: 44
Reputation: 40145
int i;// j = 0;//unused `j`
char t[] = "ayasxka";
char *r = calloc(strlen(t) + 2 + 1, sizeof(char));//change size, +2: for last a, +1: for NUL
//memset(r, '\0', (strlen(t) + 1));//calloc initialize by 0
for(i=0; t[i] != '\0'; i++){
if(t[i] == 'a'){
r[i] = '1';
r[i+1] = '2';
r[i+2] = '3';
}
else if(r[i] == '\0'){//Not yet been set to the value
r[i] = t[i];
}
}
printf("%s\n", r);//12123k123
free(r);
char t[] = "ayasxka";
int i, len = strlen(t);
char *r = calloc(len + 2 + 1, sizeof(char));
for(i=len-1; i>=0; --i){
if(t[i] == 'a'){
r[i] = '1';
r[i+1] = '2';
r[i+2] = '3';
}
else if(r[i] == '\0'){
r[i] = t[i];
}
}
printf("%s\n", r);//12323k123
free(r);
Upvotes: 0
Reputation: 79
In your algorithm you should use:
for(i=0; t[i] != '\0'; i++)
{
if(t[i] == 'a')
{
j = i;
r[j++] = '1';
r[j++] = '2';
r[j++] = '3';
}
else if(j==i)
r[j++] = t[i];
}
r[j] = '\0';
and in your malloc
you should add +1 character for the '\0'
, because strlen()
doesn't count that, so
char *r = malloc(3 + strlen(t));
instead of
char *r = malloc(2 + strlen(t));
This will give you 12123k123
Upvotes: 2
Reputation: 53016
The problem is strlen(t) + 2
is not enough, consider the worst case i.e. the string is just made of only a
characters, then it should be
char *r = malloc(3 * strlen(t) + 1);
and szieof(char) == 1
is madatory by the way.
And you will need a counter for the position in the r
string, say j
Try this
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main()
{
int i, j = 0;
char t[] = "ayasxka";
/* don't call strlen multiple times, store the value if it wont change */
size_t length = strlen(t);
/* it doesn't matter how unlikely malloc will fail, check that + */
char *r = malloc(3 * length + 1); /* | */
if (r == NULL) /* <--------------------------------------------+ */
return -1;
for (i = 0 ; t[i] != '\0' ; i++)
{
if(t[i] == 'a')
{
r[j++] = '1';
r[j++] = '2';
r[j++] = '3';
}
else
r[j++] = t[i];
}
/* you don't need the memset */
r[j] = '\0';
printf("%s\n", r);
free(r);
return 0;
}
Upvotes: 2