I have a char array containing a number.
char number[] = "12000000"
I need to have a function to insert a divider in every 3 digits. Like:
char result[] = "12,000,000"
My function accepts the number as a char pointer and it needs to return result as a char pointer too.
char* insert_divider(char* number) {
some magic;
return result;
}
I have no idea of working with pointers. Thanks.
Here you have a function that adds char c every num characters starting from the end. You need to make sure that the string buffer is long enough to accommodate the amended string.
char *addEvery(char *str, char c, unsigned num)
{
char *end = str;
if(str && *str && num)
{
size_t count = 1;
while(*(end)) end++;
while(end != str)
{
end--;
count++;
if(!(count % (num + 1)) && str != end)
{
memmove(end + 1, end, count);
*end = c;
count++;
}
}
}
return str;
}
int main(void)
{
char str[100] = "120000000000";
printf("%s", addEvery(str,',',3));
}
I came up with this piece of code:
char *result;
result = (char*) malloc(15);
int len= strlen(input);
uint8_t cursor= 0;
for(int i = 0; i < len; i++) {
if ((len- i) > 0 && (len- i) % 3 == 0) {
result[i + cursor] = ',';
cursor++;
}
result[i + cursor] = input[i];
}
result[len+ cursor] = '\0';
Thanks everyone for help and advice.
Here is another way to do it:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* insert_divider(char* number, size_t length) {
int j = length + length/3; // every 3 digits a ',' will be inserted
char *out = (char*)malloc(j + 1);
out[j--] = '\0';
for (int i = length - 1, k = 1; i >= 0; i--, k++) {
out[j--] = number[i];
if ((k%3) == 0) {
out[j--] = ',';
}
}
return out;
}
int main(){
char number[] = "12000000";
char *outNumber = insert_divider(number, strlen(number));
printf("%s", outNumber);
free(outNumber);
return 0;
}
Related
Let's suppose i have this phrase:
Hello $, Welcome!
I have to replace the '$' with a name, the result should be:
Hello Name, Welcome!
For now i did this, but it copies only the name and the first part of the phrase:
char * InsertName(char * string, char * name)
{
char temp;
for(int i = 0; i < strlen(string); i++)
{
if(string[i] == '$')
{
for(int k = i, j = 0; j < strlen(name); j++, k++)
{
temp = string[k+2];
string[k] = name[j];
string[k+1] = temp;
}
return string;
}
}
return "";
}
How can i shift all the elements after the name, so i can have the full string to be returned?
You can use sprintf() to print the output on a C-string, emulating the work done by printf():
Edit: You will have to include these two headers for this function to work:
#include <stdlib.h>
#include <memory.h>
An implementation of what you are trying to implement:
char* InsertAt(unsigned start, const char* source, const char* target, const char* with,
unsigned * position_ret)
{
const char * pointer = strstr(source, target);
if (pointer == NULL)
{
if (position_ret != NULL)
*position_ret = UINT_MAX;
return _strdup(source);
}
if (position_ret != NULL)
*position_ret = (unsigned)(pointer - source);
char* result = calloc(strlen(source) + strlen(with) + strlen(pointer), sizeof(char));
sprintf_s(result, strlen(source) + strlen(with) + strlen(pointer), "%.*s%.*s%.*s",
(signed)(pointer - source), _strdup(source),
(signed)strlen(with) + 1, _strdup(with),
(signed)(strlen(pointer) - strlen(target)), _strdup(pointer + strlen(target)));
return result;
}
Example:
#define InsertAtCharacter(src, ch, with) InsertAt(0u, (src), \
(char[]){ (char)(ch), '\0' }, (with), NULL)
int main(void)
{
printf("%s", InsertAtCharacter("Hello $, Welcome!", '$', "Name"));
return 0;
}
Try this !!!
#include <stdio.h>
#include <string.h>
char* replace(char* str, char* a, char* b)
{
int len = strlen(str);
int lena = strlen(a), lenb = strlen(b);
for (char* p = str; p = strstr(p, a); ++p) {
if (lena != lenb) // shift end as needed
memmove(p+lenb, p+lena,
len - (p - str) + lenb);
memcpy(p, b, lenb);
}
return str;
}
int main()
{
char str[80] = "Hello $,Welcome!";
printf("%s\n", replace(str, "$", "name"));
return 0;
}
I would like to fit a string into multiple rows of a fixed width. I managed to separate the string into different rows so that their length will not pass the fixed width, but the problem is that some rows are not width (80) characters long, this is why I am trying to distribute the extra_space by adding spaces between words.
#include <stdio.h>
#include <string.h>
#include "stringdefault.h"
#include <conio.h>
#include <stdlib.h>
int main(){
int width = 80;
char s1[10000];
char substring[100] = " ";
char space = ' ';
gets(s1);
removeSpaces(s1);
char *base,*right_margin;
int extraSpace, numWords, numSpaces, incrementEachSpaceby, ind1, ind2, k;
int length;
length = string_length(s1);
base = s1;
for(int i = 0; i < width; i++)
{
printf("%d", i%10);
}
printf("\n");
while(*base)
{
if(length <= width)
{
puts(base); // display string
return(0); //and leave
}
right_margin = base+width;
while(!isspace(*right_margin))
{
right_margin--;
if( right_margin == base)
{
right_margin += width;
while(!isspace(*right_margin))
{
if( *right_margin == '\0')
break;
right_margin++;
}
}
}
*right_margin = '\0';
if(string_length(base) < width)
{
char *newStr = malloc(width);
extraSpace = width - string_length(base);
numWords = numberOfWords(base);
numSpaces = numWords - 1;
incrementEachSpaceby = extraSpace/numSpaces;
ind1 = 0;
ind2 = 0;
while (ind2 < width)
{
newStr[ind2] = base[ind1];
ind1++;
ind2++;
}
for(int i = 0; newStr[i]!='\0'; i++)
if((isspace(newStr[i])))
{
if(extraSpace > 0)
k = extraSpace;
else
k = 1;
while(k)
{
insert_substring(newStr, substring, i);
k--;
}
}
puts(newStr);
}
else
puts(base);
length -= right_margin-base+1; // +1 for the space
base = right_margin+1;
}
return 0;
}
stringdefault.h
int string_length(char s[])
{
int length = 0;
for(int i=0; s[i]!='\0'; i++)
length++;
return length;
}
char *substring(char *string, int position, int length)
{
char *pointer;
int c;
pointer = malloc(length+1);
if( pointer == NULL )
exit(EXIT_FAILURE);
for( c = 0 ; c < length ; c++ )
*(pointer+c) = *((string+position-1)+c);
*(pointer+c) = '\0';
return pointer;
}
void insert_substring(char *a, char *b, int position)
{
char *f, *e;
int length;
length = strlen(a);
f = substring(a, 1, position - 1 );
e = substring(a, position, length-position+1);
strcpy(a, "");
strcat(a, f);
free(f);
strcat(a, b);
strcat(a, e);
free(e);
}
char *removeSpaces(char *str)
{
int ip_ind = 0;
char *ptr;
while(*(str + ip_ind))
{
if ( (*(str + ip_ind) == *(str + ip_ind + 1)) && (*(str + ip_ind)==' ') )
{
ptr = str + ip_ind+1;
do{
*(ptr-1) = *ptr;
}while(*ptr++ != '\0');
}
else
ip_ind++;
}
*(str + ip_ind) = '\0';
return str;
}
The output that I get without the while loop inside the if statement
It seems that the newStr set of characters, contains spaces before it's first character.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Right now I can replace the word indifferent in the given string with nonchalant but I need to make this function dynamic so indifferent can be replaced with any word. I know i need to use malloc to create a new array that will hold my original string with the new word but don't have a strong understanding of how to use malloc yet, Please explain how to use malloc properly in this situation. Thank you.
#include <stdio.h>
#include <stdlib.h>
int findPosition(char string[], char sub[]) {
int i = 0;
int j = 0;
int f = 0;
for (i = 0; string[i] != '\0'; i++) {
if (sub[j] == string[i]) {
if (sub[j + 1] == '\0') {
f = 1;
break;
}
j++;
} else
j = 0;
}
if (f == 1) {
return i - j;
}
return -1;
}
int findLength(char sub[]) {
int i = 0;
for (i = 0; sub[i] != '\0'; i++) {
}
return i;
};
void replaceWord(char string[], char sub[], char replace[]) {
int i = 0;
int j = 0;
int p = findPosition(string, sub);
int l = findLength(sub);
int k = p + l - 1;
for (i = p; i < k; i++) {
string[i] = replace[j];
j++;
}
while(string[k] != '\0') {
string[k] = string[k + 1];
k++;
}
}
int main(int argc, const char *argv[]) {
char stringArray[120] = "\"Mr.Fay, is this going to be a battle of wits? \""
"\t\"If it is,\" was the indifferent retort, \""
"you have come unarmed!\"";
replaceWord(stringArray, "indifferent", "nonchalant");
int i = 0;
while (stringArray[i] != '\0') {
printf("%c", stringArray[i]);
i++;
}
return 0;
};
You can use malloc to allocate memory for the new string where you replace each occurrence of one word with another word:
#include <stdio.h>
#include <stdlib.h>
/* use a local implementation of the string functions: */
size_t my_strlen(const char *s) {
size_t len;
for (len = 0; s[len] != '\0'; len++)
continue;
return len;
}
void *my_memcpy(void *dest, const void *src, size_t n) {
size_t i;
for (i = 0; i < n; i++) {
((unsigned char*)dest)[i] = ((unsigned char*)src)[i];
}
return dest;
}
char *my_strdup(const char *s) {
size_t n = my_strlen(s) + 1;
char *p = malloc(n);
if (p) my_memcpy(p, s, n);
return p;
}
char *my_strstr(const char *s1, const char *s2) {
for (;; s1++) {
for (size_t i = 0;; i++) {
if (s2[i] == '\0') return s1;
if (s1[i] != s2[i]) break;
}
if (*s1 == '\0') return NULL;
}
}
char *replaceWord(const char *str, const char *s1, const char *s2) {
char *res = my_strdup(str); /* return value is always allocated */
char *p, *q;
size_t offset = 0;
size_t len = my_strlen(str);
size_t len1 = my_strlen(s1);
size_t len2 = my_strlen(s2);
if (len1 == 0)
return res;
while ((p = my_strstr(res + offset, s1)) != NULL) {
offset = p - res;
if (len1 == len2) {
/* no need to reallocate, replace in place */
my_memcpy(res + offset, s2, len2);
} else {
/* allocate a new array with the adjusted length */
q = malloc(len + len2 - len1 + 1);
/* copy the beginning of the string */
my_memcpy(q, res, offset);
/* copy the replacement string */
my_memcpy(q + offset, s2, len2);
/* copy the remainder of the string, and the final '\0' */
my_memcpy(q + offset + len2, res + offset + len1, len - offset - len1 + 1);
/* free the previous string */
free(res);
res = q;
}
/* search for matches from the end of the replacement */
offset += len2;
}
return res;
}
int main(int argc, const char *argv[]) {
char stringArray[120] = "\"Mr.Fay, is this going to be a battle of wits? \""
"\t\"If it is,\" was the indifferent retort, \""
"you have come unarmed!\"";
char *p = replaceWord(stringArray, "indifferent", "nonchalant");
printf("%s", p);
free(p);
return 0;
}
char num = '5';
strcpy(array, "2,3,7,9")
Hi guys, any ideas if want to insert 5 into the array according to the value which will result in, how would i go about doing this?
array = "2,3,5,7,9"
#include <stdio.h>
#include <string.h>
void insert_string(char *target, const char *to_insert, int index) {
int count = 0;
int i;
int move_dst;
int insert_comma = 0;
int to_len = strlen(to_insert);
if (index < 0) index = 0;
if (index <= 0) {
i = 0;
} else {
for (i = 0; target[i] != '\0'; i++) {
if (target[i] == ',') {
count++;
if (count >= index) {
i++;
break;
}
}
}
}
/* i is where to insert the string */
if (target[i] == '\0') {
/* the insertion target was end of the string */
target[i] = ',';
target[++i] = '\0';
}
move_dst = i + to_len;
if (target[i] != '\0') {
/* the sequence continues after insertion point */
move_dst++;
insert_comma = 1;
}
memmove(&target[move_dst], &target[i], strlen(&target[i]) + 1); /* copy includes termination '\0' */
memcpy(&target[i], to_insert, to_len);
if (insert_comma) target[i + to_len] = ',';
}
int main(void) {
char array[1024];
char num = '5';
char num_string[2] = {num, '\0'};
int c = 2;
strcpy(array, "2,3,7,9");
puts(array);
insert_string(array, num_string, c);
puts(array);
return 0;
}
I am currently learning C with the book "Programming in C 3rd edition" by Stephen G. Kochan.
The exercise require that I make a function that replaces a character string inside a character string with another character string. So the function call
replaceString(text, "1", "one");
Will replace, if exist, "1" in the character string text with "one".
To fullfill this exercise, you need the functions findString(), insertString() and removeString().
This is the findString() function
int findString (const char source[], const char s[])
{
int i, j;
bool foundit = false;
for ( i = 0; source[i] != '\0' && !foundit; ++i )
{
foundit = true;
for ( j = 0; s[j] != '\0' && foundit; ++j )
if ( source[j + i] != s[j] || source[j + i] == '\0' )
foundit = false;
if (foundit)
return i;
}
return -1;
}
If s[] is inside the string source[], it returns an integer equal to the starting point for s[] inside the string. If it do not find s[] it will return -1.
The insertString() function is as follows
void insertString (char source[], char s[], int index)
{
int stringLength (char string[]);
int j, lenS, lenSource;
lenSource = stringLength (source);
lenS = stringLength (s);
if ( index > lenSource )
return;
for ( j = lenSource; j >= index; --j )
source[lenS + j] = source[j];
for ( j = 0; j < lenS; ++j )
source[j + index] = s[j];
}
This function take three arguments i.e. source[], s[] and index[]. s[] is the string that I would like to put into source[] and index[] is where it should start (e.g. insertString("The son", "per", 4) makes the source string to "The person").
The function includes another function called stringLength(), which purpose is the same at its name. This is stringLength()
int stringLength (char string[])
{
int count = 0;
while ( string[count] != '\0' )
++count;
return count;
}
The removeString() takes three arguments i.e. word, i and count. The function removes a number of characters inside another character string. This function I have not yet been able to make.
Just to sum it up, my question is:
How do i make the function replaceString(), which looks for a word in a character string, and if it is there, then it replaces it with another?
This has really bugged me for some time, and I would really appreciate your help on this.
UPDATE
This is the code I have made so far
// replaceString() program
#include <stdio.h>
#include <stdbool.h>
int findString (char source[], char s[])
{
int i, j;
bool foundit = false;
for ( i = 0; source[i] != '\0' && !foundit; ++i )
{
foundit = true;
for ( j = 0; s[j] != '\0' && foundit; ++j )
if ( source[j + i] != s[j] || source[j + i] == '\0' )
foundit = false;
if (foundit)
return i;
}
return -1;
}
int stringLength (char string[])
{
int count = 0;
while ( string[count] != '\0' )
++count;
return count;
}
void replaceString(char source[], char str1[], char str2[])
{
int findString(char source[], char s[]);
int stringLength(char string[]);
int start;
if ( findString(source, str1) == -1 )
return;
else
{
start = findString(source, str1);
int lenSource = stringLength(source);
int lenStr2 = stringLength(str2);
int counter = lenStr2;
for ( lenSource; lenSource > start + lenStr2; --lenSource )
{
source[lenSource + lenStr2] = source[lenSource];
}
int i = 0;
while ( i != counter )
{
source[start + i] = str2[i];
++i;
}
}
}
int main (void)
{
void replaceString(char source[], char str1[], char str2[]);
char string[] = "This is not a string";
char s1[] = "not";
char s2[] = "absolutely";
printf ("Before: \n %s \n\n", string);
replaceString(string, s1, s2);
printf ("After: \n %s \n\n", string);
return 0;
}
This code gives the following output:
Before:
This is not a string
After:
This is absolutelyng
As you can see, I have not included the removeString function(), as I could not get that function working properly. Where is the error in my program?
for starters, your string's length is fixed. so if the "destination" is longer than "source", then it won't work. insert string needs to pass in a pointer, then you can allocate a string on the heap that is long enough to contain length(source)-length(remove) +length(add), and return that pointer
Say your replaceString() args are (char source[], char s1[], char replacement[])
You need to use findString() to find s1 in source. If it finds it, given the position of s1, use removeString() to remove that string and then insertString() to insert replacement into that position.
I am also a newbie in programming. I came across this same exercise some days ago and just solved it today.
This is my code.
/* Programme to replace a string by using find, remove and insert
functions ex9.8.c */
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define MAX 501
// Function prototypes
void read_Line (char buffer[]);
int string_Length (char string[]);
int find_String (char string1[], char string2[]);
void remove_String (char source[], int start, int number);
void insert_String (char source[], int start, char input[]);
void replace_String (char origString[], char targetString[], char substString[]);
bool foundFirstCharacter = false;
int main(void)
{
printf("This is a programme to replace part of a string.\n");
printf("It can only handle up to 500 characters in total!\n");
char text[MAX];
bool end_Of_Text = false;
int textCount = 0;
printf("\nType in your source text.\n");
printf("When you are done, press 'RETURN or ENTER'.\n\n");
while (! end_Of_Text)
{
read_Line(text);
if (text[0] == '\0')
{
end_Of_Text = true;
}
else
{
textCount += string_Length(text);
}
break;
}
// Declare variables to store seek string parameters
int seekCount = 0;
char seekString[MAX];
printf("\nType in the string you seek.\n");
printf("When you are done, press 'RETURN or ENTER'.\n\n");
while (! end_Of_Text)
{
read_Line(seekString);
if (seekString[0] == '\0')
{
end_Of_Text = true;
}
else
{
seekCount += string_Length(seekString);
}
break;
}
// Declare variables to store replacement string parameters
int replCount = 0;
char replString[MAX];
printf("\nType in the replacement string.\n");
printf("When you are done, press 'RETURN or ENTER'.\n\n");
while (! end_Of_Text)
{
read_Line(replString);
if (replString[0] == '\0')
{
end_Of_Text = true;
}
else
{
replCount += string_Length(replString);
}
break;
}
// Call the function
replace_String (text, seekString, replString);
return 0;
}
// Function to get text input
void read_Line (char buffer[])
{
char character;
int i = 0;
do
{
character = getchar();
buffer[i] = character;
++i;
}
while (character != '\n');
buffer[i - 1] = '\0';
}
// Function to determine the length of a string
int string_Length (char string[])
{
int len = 0;
while (string[len] != '\0')
{
++len;
}
return len;
}
// Function to find index of sub-string
int find_String (char string1[], char string2[])
{
int i, j, l;
int start;
int string_Length (char string[]);
l = string_Length(string2);
for (i = 0, j = 0; string1[i] != '\0' && string2[j] != '\0'; ++i)
{
if (string1[i] == string2[j])
{
foundFirstCharacter = true;
++j;
}
else
{
j = 0;
}
}
if (j == l)
{
start = i - j + 1;
return start;
}
else
{
return j - 1;
}
}
// Function to remove characters in string
void remove_String (char source[], int start, int number)
{
int string_Length (char string[]);
int i, j, l;
char ch = 127;
l = string_Length(source);
j = start + number;
for (i = start; i < j; ++i)
{
if (i >= l)
{
break;
}
source[i] = ch;
}
//printf("\nOutput: %s\n", source);
}
// Function to insert characters in string
void insert_String (char source[], int start, char input[])
{
int string_Length (char string[]);
int i, j, k, l, m;
int srcLen;
int inpLen;
int totalLen;
int endInsert;
srcLen = string_Length(source);
inpLen = string_Length(input);
// Declare buffer array to hold combined strings
totalLen = srcLen + inpLen + 3;
char buffer[totalLen];
// Copy from source to buffer up to insert position
for (i = 0; i < start; ++i)
buffer[i] = source[i];
// Copy from input to buffer from insert position to end of input
for (j = start, k = 0; k < inpLen; ++j, ++k)
buffer[j] = input[k];
endInsert = start + inpLen;
for (m = start, l = endInsert; m <= srcLen, l < totalLen; ++m, ++l)
buffer[l] = source[m];
buffer[l] = '\0';
printf("\nOutput: %s\n", buffer);
}
// Function to replace string
void replace_String (char origString[], char targetString[], char substString[])
{
// Function prototypes to call
void read_Line (char buffer[]);
int string_Length (char string[]);
int find_String (char string1[], char string2[]);
void remove_String (char source[], int start, int number);
void insert_String (char source[], int start, char input[]);
// Search for target string in source text first
int index;
index = find_String (origString, targetString);
if (index == -1)
{
printf("\nTarget string not in text. Replacement not possible!\n");
exit(999);
}
// Remove found target string
int lengthTarget;
lengthTarget = string_Length(targetString);
remove_String(origString, index - 1, lengthTarget);
// Insert replacement string
insert_String(origString, index, substString);
}