Replace one character with multiple characters - c

I need to replace " " (space) with ", " (comma and space).
I have function which receive string as char* and after replacing all this characters prints string on screen.
char* PrintComma(char* Text) {
for (int i = 0; i < strlen(Text); i++) {
if (Text[i] == ' ') {
Text[i] = ',';
}
}
return Text;
}
This replaces " " with "," but I need ", ". I'm not allowed to use a second string or array for saving temp data. I can use only this one string.
Example:
Input => "Hello world my name is"
Output => "Hello, world, my, name, is"

This problem seems like a perfect setup for memmove() which is a library function that copies bytes between two strings but handles overlapping memory blocks.
memmove(
char_pointer + make_room_at + room_to_make,
char_pointer + make_room_at,
init_size - make_room_at + room_to_make
);
Here is the application using memmove().
char* PrintComma(char* Text) {
for (int i = 0; i < strlen(Text); i++) {
if (Text[i] == ' ') {
memmove(
Text + i + 1,
Text + i,
strlen(Text) - i + 1
);
Text[i++] = ',';
}
}
return Text;
}

Here's a working example. The input buffer must be large enough to store the replaced string, as the requirements state that no new string should be created.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void PrintComma(char* Text)
{
char* str = Text;
size_t c, len = strlen(Text);
for (c = 0; Text[c]; Text[c] == ' ' ? c++ : *Text++);
for (size_t i = 0; i < len + c; i++)
{
if (str[i] == ' ')
{
str[i] = ',';
char last = ' ';
for(size_t u = i + 1; u < len + c; u++)
{
char current = str[u];
str[u] = last;
last = current;
}
i += 2;
}
}
}
int main(void)
{
char tmp[100] = { 0 };
const char* TEST = "Hello world my name is";
memcpy(tmp, TEST, strlen(TEST));
printf("Input: %s\n", tmp);
PrintComma(tmp);
printf("Output: %s\n", tmp);
return 0;
}
Result:
Input: Hello world my name is
Output: Hello, world, my, name, is

Based on your requirements:
I have function which receive string as char* and after replacing all this characters prints string on screen.
I don't think you're looking to replace a space with a comma-space. Instead, I think you want to go through the string and print all the characters. When you encounter a space, you print an extra comma. Here's roughly how to do that:
void PrintComma(char *text)
{
const size_t len = strlen(text); // don't call on every iteration
for(size_t i = 0; i < len; i++)
{
if(text[i] == ' ')
putchar(',');
putchar(text[i]);
}
}

You have two requirements:
1) The spaces must be replaced.
2) You cannot use another char array.
These lead to the assumption that the input char* must have adequate allocated space for all the new ,s.
In that case, this would work.
char *PrintComma(char *Text) {
int numberOfSpaces = 0, orignalLength = strlen(Text);
for (int i = 0; i < strlen(Text); i++) {
if (Text[i] == ' ')
numberOfSpaces++;
}
for (int i = orignalLength - 1, j = orignalLength + numberOfSpaces - 1; i >= 0; i--) {
Text[j] = Text[i];
j--;
if (Text[i] == ' ') {
Text[j] = ',';
j--;
}
}
return Text;
}

Related

turning morse into english from a txt file in C, only iterates 1 char in the string before stopping

Using the code below it only reads one char and does not convert morse to letter. My idea was to create a string of one morse "letter" and put it in the convert function, however only 1 char is being read since I am only seeing a single 1 printed on the screen after the string itself is printed. The string only consists of '-' , '.' , ' '. I was wondering if anyone knows what the solution might be.
char convertToLetter(M* data, char word[10]) {
int size = 0;
char correct;
while (size < 60)
{
int compare = strcmp(word, data->morse);
if (compare == 0) {
correct = data->letter;
}
data++;
size++;
}
correct = '\0';
return correct;
}
int main(){
//some code here for opening a file.
char curSent[200];
char letter[6] = "";
int i = 0;
char* fullString = (char*)malloc(1000 * sizeof(char));
fullString[0] = '\0';
while (fgets(curSent, 200, inFile) != NULL) {
if (curSent[0] != '\n') {
curSent[strlen(curSent) - 1] = '\0';
strcat_s(fullString,1000, curSent);
}
else {
printf("%s", fullString);
printf("\n\n");
int j = 0;
while (i < strlen(fullString)) {
if (fullString[i] != ' ') {
fullString[i] = letter[j];
i++;
j++;
printf("%d \n", 1);
}else if (fullString[i + 1] == ' ' && fullString[i] == ' ') {
printf("%d", 2);
printf(" %c", convertToLetter(dictionary, letter));
memset(letter, 0, strlen(letter));
j = 0;
i = i + 2;
}else if (fullString[i] == ' ') {
printf("%d", 3);
printf("%c", convertToLetter(dictionary, letter));
memset(letter, 0, strlen(letter));
j = 0;
i = i++;
}
}
memset(fullString, 0, strlen(fullString));
i = 0;
}
}
//printf("%s", fullString);
getchar();
return 0;
}

Reading In txt File and Extracting Elements from Input Problem

I have been attempting to fix this for hours. I am trying to read a file called wiktionary called "stuff.txt" which has input of the form:
10000
5627187200 the
3395006400 of
2994418400 and
2595609600 to
1742063600 in
...
The 10000 represents the number of lines. I am then reading it in using a function read_in_terms, and extracting the number (weight) and the word (word) from it. I have tested my get_word and get_weight functions seperately and they seem to be working. However, when I am reading in, my get_word function is not returning the word .... the get_weight number is...
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char* concat(const char *s1, const char *s2) {
char *result = malloc(strlen(s1) + strlen(s2) + 1);
strcpy(result, s1);
strcat(result, s2);
return result;
}
// from a string of the form " 29480398934 the" it returns number
long get_weight(char *string) {
long length = strlen(string);
char number[200];
int count = 0;
// Here I am cycling through until X__X combination
// I only add to the number if it is not " "
for (int i = 0; i < length; i++) {
if (string[i-1] != ' ' && string[i] == ' ' && string[i+1] == ' ' && string[i+1] != ' ') {
break;
} else if (string[i] != ' '){
number[count] = string[i];
count++;
}
}
number[count] = '\0';
return atol(number); // converts it to a long and then returns
}
// from a string of the form " 453495834 word" it returns word
char * get_word(char* string) {
long length = strlen(string);
char word[200];
int count = 0;
// the double space detection only works once we reach a character
// this becomes 1 once that happens, allowing us to proceed to the next part
int blocker = 0;
for (int i = 0; i < length; i++) {
if (string[i] != ' '){
blocker++;
}else if (blocker > 0 && string[i] == ' ' && string[i+1] == ' ') {
int int_count = i+1;
while (string[int_count] != '\0') {
int_count++;
word[count] = string[int_count];
count++;
}
}
}
word[count] = '\0';
// now I need to copy this string into malloc
char *str = (char *)malloc(count*sizeof(char));
strcpy(str, word);
return str;
}
void read_in_terms(int *pnterms, char *filename) {
char part1[] = "/Users/adammartinez/Desktop/";
char* title = concat(part1,filename);
FILE *fp = fopen(title, "r");
char line[200];
fgets(line, sizeof(line), fp);
int num_lines = atoi(line);
for (int i = 0; i < num_lines; i++){
fgets(line, sizeof(line), fp);
printf("%ld \n", get_weight(line));
printf("%s \n", get_word(line)); // NOT RETURNING WORDS
}
}
int main(void) {
//char* test_str = " 547584758475 the";
//printf("%s %ld", get_word(test_str), get_weight(test_str));
int terms = 1000;
int *pointer = &terms;
read_in_terms(pointer, "stuff.txt");
return 0;
}
It seems to work fine on my computer. Please look at the output below and tell me if it's what you're looking for. I set part1 to "" and I changed the number of lines in stuff.txt to 5.
5627187200
the
3395006400
of
2994418400
and
2595609600
to
1742063600
in

The program returns some weird and incomplete string

I am trying to write a function that delete whitespaces from a string but the output is not reasonable at all. I need help fam!
Code:
char* deleteSpace(char *String, int n) {
int i;
char* withoutSpaces;
withoutSpaces = calloc(n, sizeof (char));
for (i = 0; i < n - 1; i++) {
if (String[i] == ' ')
withoutSpaces[i] = String[++i];
else
withoutSpaces[i] = String[i];
}
return withoutSpaces;
}
You need to have to indices a "read" index for the source string and a "write" index for the destination.
Also, for better debugability and readability, put the index increment, ++i on a separate line. Oh - it looks like you are incrementing i twice. Once implicitly by the loop and again with the ++i.
Also unclear if n represents the length of the string with or without the null terminator. So let's just let the function deal with figuring that out via strlen.
Don't forget to null terminate the output string.
Several other bugs as well. Here's a version that's improved:
char* deleteSpace(const char *String) {
int j = 0;
const char* ptr = String;
size_t n = 0;
size_t spaces = 0;
char* withoutSpaces = NULL;
// count how many characters we expect to copy over
while (*ptr) {
n += (*ptr == ' ') ? 0 : 1;
ptr++;
}
withoutSpaces = (char*)malloc(n+1); // +1 for null char
for (i = 0; i < n; i++) {
if (String[i] != ' ') {
withoutSpaces[j] = String[i];
j++;
}
}
withoutSpaces[j] = '\0';
return withoutSpaces;
}
Also, if you just want to compact the string in place without allocating a new string.
void deleteSpace(char *String) {
char* ptrWrite = String;
while (*String) {
if (*String != ' ') {
*ptrWrite = *String;
ptrWrite++;
}
String++;
}
*ptrWrite = '\0';
}

Function and strings

I'm new to C and have started learning about strings. I want to create a function called
void SpaceRemover(char *input )
It should remove the spaced from a given string array that has lots of space
The code that I've produced so far removes all the spaces and doesn't provide the output I'm looking for. Can anyone help me with this?
char* SpaceRemover(char *input){
char *output=input;
for (int i = 0, j = 0; i<strlen(input); i++,j++)
{
if (input[i]!=' ')
output[j]=input[i];
else
j--;
}
return output;
}
I made this but I know its wrong and does not do what i want it to but honestly this is all i could this of -_-
You could just do as below
void SpaceRemover(char *name)
{
int i=0,j=0;
for (i = 0;i<strlen(name);i++)
{
if (name[i] != ' ' || (name[i] == ' ' && name[i+1] != ' ' && j!= 0))
{
name[j++] = name[i];
}
}
name[j]='\0'; //Terminate the string to avoid junk chars
}
Where
if (name[i] != ' ' || (name[i] == ' ' && name[i+1] != ' ' && j != 0))
will let you copy only if current char is not space or current char is space and next char is not space(to include single space apart in the beginning).
Also don't forget to terminate the string.
name[j]='\0';
The problem is that you remove all spaces.
char *SpaceRemover(char *name){
char *output = name;
int j = 0;
for (int i = 0; i < strlen(name); i++) {
if (name[i] != ' ' || (name[i] == ' ' && name[i + 1] != ' ') {
output[j] = name[i];
j += 1;
}
}
output[j] = '\0'
return output;
}
This condition should let one space through.
You might notice I replaced the void return type with a char * so t o use the function you will need to use:
name = SpaceRemover(name);
I would be using a flag to activate when a space is met.
This might need to be tweaked if you want to remove leading and trailing spaces too.
A space will be added to output and the flag will be used to avoid the next ones to be added. The flag will be deactivated when something else than a space is met.
As stated Alex in comments, decrementing j in loop while it's incremented in the for statement isn't recommended.
I would copy each characters in the for loop instead of filtering a pre-copied output.
char space_found = 0;
char *output = malloc(sizeof(char) * (strlen(name) + 1));
int j = 0;
for (int i = 0; i < strlen(name); ++i)
{
if (name[i] == ' ' and space_found == 0)
{
space_found = 1;
output[j++] = name[i];
}
if (name[i] != ' ')
{
space_found = 0;
output[j++] = name[i];
}
}
output[j] = '\0';
void spaceRemover(char* str)
{
char temp[50] = {0};
int j = 0;
strncpy(temp, str, strlen(str) + 1);
for(int i = 0; i < strlen(str); i++)
{
if(temp[i] != ' ')
{
str[j] = temp[i];
j++;
}
}
str[j] = 0;
}
if you have any questions, feel free to ask, Good Luck
#include <stdio.h>
char *rem(char *str)
{
char *cur=str;
char *nex=str;
while(*nex)
{
if(*nex == ' ') nex++;
else *cur++ = *nex++;
}
*cur=0;
return str;
}
int main(void) {
char z[]=" etc def etc def ";
printf("%s\n", rem(z));
return 0;
}

Reverse words in C Language

I'm trying to reverse the letters for words in a sentence. I am also trying to store these words in a new char array. At the moment I getting a runtime error, which for all my tweaking I can not solve. My approach is to create a new char array the same length as the sentence. Then loop through the sentence until I reach a ' ' character. Then loop backwards and add these characters to a word. Then add the word to the new Sentence. Any help would be much appreciated.
int main(void) {
char sentence [] = "this is a sentence";
char *newSentence = malloc(strlen(sentence)+1);
int i,j,start;
start = 0;
for(i = 0; i <= strlen(sentence); i++)
{
if(sentence[i] == ' ')
{
char *word = malloc((i - start)+1);
for(j = sentence[i]; j >= start; j--)
{
word[j] = sentence[j];
}
strcat(newSentence,word);
start =sentence[i +1];
}
}
printf("%s",newSentence);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char sentence [] = "this is a sentence";
char *newSentence;
int i,j,start, len;
start = 0;
len = strlen(sentence);
newSentence = malloc(len+1);
*newSentence = '\0';
for(i = 0; i <= len; i++)
{
if(sentence[i] == ' ' || sentence[i] == '\0')
{
char *word = malloc((i - start)+1);
int c = 0;
for(j = i - 1; j >= start; j--)
{
word[c++] = sentence[j];
}
word[c]='\0';
strcat(newSentence,word);
if(sentence[i] == ' ')
strcat(newSentence," ");
start = i + 1;
free(word);
}
}
printf("%s",newSentence);
return 0;
}
Logically, here:
j = sentence[i]
start =sentence[i +1];
start and j are index positions in the char array, you are trying to assign a char to them, which screws everything up.
should be:
j= i;
start = i +1;
if your algorithm is right.
Yet another variant of the same...
int main(int argc, const char *argv[])
{
char sentence [] = "this is a sentence";
size_t len = strlen(sentence);
char *newSentence = malloc(len + 1);
char *ptr_src = sentence;
char *ptr_dst = newSentence;
while(ptr_src)
{
char *next, *t;
next = strchr(ptr_src, ' '); // find next space
if (!next) next = sentence + len; // if not found, next = EOL
for (t = next; t > ptr_src;)
{
*ptr_dst++ = *--t;
}
if (*next)
{
*ptr_dst++ = *next++;
ptr_src = next;
}
else
{
*ptr_dst = 0;
break;
}
}
printf("[%s]",newSentence);
return 0;
}
Your program had few bugs. Which I've tried to remove in this program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char sentence [] = "this is a sentence";
char *newSentence = (char *)malloc(strlen(sentence)+1);
int i,j,start, k;
start = 0;
for(i = 0;; i++)
{
if(sentence[i] == ' ' || sentence[i] == '\0') //sentence[i] == '\0' for the last word.
{
char *word = (char *) malloc((i - start)+1);
for(j = i-1, k = 0; j >= start; j--, k++)
{
word[k] = sentence[j];
}
word[k++] = ' '; //space after each word
word[k] = '\0';
strcat(newSentence,word);
start = i+1;
}
if (sentence[i] == '\0')
break;
}
printf("%s\n",newSentence);
return 0;
}
Check live at http://ideone.com/Z9ogGk
strcat(newSentence,word);
newSentence has to be a string. And a string is a contiguous sequence of characters terminated by and including the first null character
EDIT: this answer has been downvoted 4 times for what is written above. If you think it is incorrect, please explain. Otherwise please remove your downvote.

Resources