char *r, *w;
for (w = r = str; *r; r++) {
    if (*r != ',') {
        *w++ = *r;
    }
}
*w = '\0';
Answer from melpomene on Stack Overflow
🌐
Quora
quora.com β€Ί How-do-you-replace-spaces-with-a-comma-in-a-string-in-C
How to replace spaces with a comma in a string in C - Quora
Quora is a place to gain and share knowledge. It's a platform to ask questions and connect with people who contribute unique insights and quality answers.
Discussions

strip commas from string
Hello all! I've been looking for a way to strip characters from strings such as a comma. This would be great for using a comma as a delimiter. I show you what I have right now. #include #include... More on thecodingforums.com
🌐 thecodingforums.com
23
July 30, 2005
Remove spaces and commas at the end and beginning of comma separated string
Given that I can get strings like this: dog, cat, person ,people, boys, girls, people, boys, police , How would I delete the possible spaces and commas at the end and beginning of strings. So for More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2017
Remove spaces and remove a value
Hello, I basically have a data that looks like the below: 6742792667373, 6746172424429, 6749208183021 Basically, I want to remove space between each comma and also remove one value for eg: 6746172424429 What i tried: I used trim() to remove space To remove a value 6746172424429 i used ... More on community.make.com
🌐 community.make.com
4
1
July 21, 2023
Remove spaces before commas in string
Can someone please help me figure out how to remove just the spaces before the commas in a string? Example: β€œ25 RIDGEWOOD RD ,SPRINGFIELD ,VT,051560000,015(SVC)” Looking for: "β€œ25 RIDGEWOOD RD,SPRINGFIELD,VT,051560000,015(SVC)” The values in the string between the commas are dynamic. More on forum.uipath.com
🌐 forum.uipath.com
10
0
December 20, 2022
🌐
Cplusplus
cplusplus.com β€Ί forum β€Ί beginner β€Ί 222945
How to get rid of commas and replace the - C++ Forum
October 13, 2017 - Also real quick just to tell you guys it does successfully the first if statement so if (ch !='-' ) is first then it removes the - lines from the file but keeps the commas and if its if(ch==',') first then it successfully takes out the spaces and replaces them with spaces .....
🌐
C# Corner
c-sharpcorner.com β€Ί blogs β€Ί remove-space-and-new-line-from-string-and-join-using-comma1
Remove Space and New Line from String and join using Comma
December 24, 2013 - Introduction Recently my clients ... trim the space and newline and will join the string using comma's. Business users use spreadsheet to observe datas and sometimes they need search functionalities too. So if they want to search the ID's then they need to copy multiple columns cells and put it in the search textbox to search. So the Search functionality should be built using comma separated ...
🌐
The Coding Forums
thecodingforums.com β€Ί archive β€Ί archive β€Ί c++
strip commas from string | C++ | Coding Forums
July 30, 2005 - #include<iostream> #include<string> int main(int argc, char *argv[]) { using namespace std ; char people[14] = "Me,Myself,I" ; char nocommas[14] ; int i, j ; i=j=0 ; for(i = 0; i < 14; i++){ if(people != ',') nocommas = people ; if(people == ',') nocommas = ' ' ; } cout << "With commas : " << people << endl ; cout << "Without commas : " << nocommas << endl ; cout << "\n\n\n\n" ; cout << "\tNow tell me how I can store each name in a separate variable ?" << endl ; cout << "\tAnd can someone show me how to do this with string instead of char[] ?" << endl ; cout << "\t\t Thanks so much!" << endl ; return 0 ; } so as you can see it strips commas and puts a space in its place.
🌐
Make Community
community.make.com β€Ί questions
Remove spaces and remove a value - Questions - Make Community
July 21, 2023 - Hello, I basically have a data that looks like the below: 6742792667373, 6746172424429, 6749208183021 Basically, I want to remove space between each comma and also remove one value for eg: 6746172424429 What i tried: I used trim() to remove space To remove a value 6746172424429 i used ...
🌐
Coderanch
coderanch.com β€Ί t β€Ί 451947 β€Ί java β€Ί remove-spaces
How to remove spaces (Java in General forum at Coderanch)
June 30, 2009 - Once you have that established, the rest is easy. it SOUNDS like what you want is to replace every occurrence of " , " (space-comma-space) with "," (comma). Note that regular expressions in java can be a little tricky, but it should be able to do what you want... There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors ... Another way to do it would be to split the String on the ",", trim each element of the resulting String[] and rewrite the values to a comma separated String.
Find elsewhere
🌐
W3Schools
w3schools.in β€Ί c-programming β€Ί examples β€Ί remove-spaces-from-string
C Program to Remove Spaces From String - W3schools
Input String: Prompt the user to enter a string. Use the gets() or fgets() function to take input. Remove Spaces: Iterate through each character of the string.
🌐
UiPath Community
forum.uipath.com β€Ί help β€Ί activities
Remove spaces before commas in string - Activities - UiPath Community Forum
December 20, 2022 - Can someone please help me figure out how to remove just the spaces before the commas in a string? Example: β€œ25 RIDGEWOOD RD ,SPRINGFIELD ,VT,051560000,015(SVC)” Looking for: "β€œ25 RIDGEWOOD RD,SPRINGFIELD,VT,051560000,015(SVC)” The values in the string between the commas are dynamic.
Top answer
1 of 3
1

You are making the problem more difficult than it needs to be. strtok takes multiple delimiters provided in a string and will consider a sequence of any combination of the delimiters as a single delimiter. So to handle parsing your .csv file where there may or may not be spaces surrounding the comma, simply include " ,\n" (space, comma, newline) as your delimiters and then strtok will split each token removing the comma as well as any leading spaces or trailing newline.

That reduces your code to simply:

#include <stdio.h>
#include <string.h>

#define MAXC 1024      /* if you need a constant, #define one (or more) */
#define DELIM " ,\n"

int main (void) {

    char buf[MAXC];   /* buffer to hold each line */

    while (fgets (buf, MAXC, stdin)) {              /* read each line */
        char *p = buf;                              /* pointer to line */
        /* now simply use strtok to separate all tokens in line */
        for (p = strtok(p, DELIM); p; p = strtok (NULL, DELIM))
            printf ("%-8s", p);                     /* output as desired */
        putchar ('\n');                             /* tidy up with newline */
    }
    return 0;
}

Example Use/Output

$ ./bin/strtokcsv <dat/spacecomma.csv
10      bob     18      3.5
15      mary    20      4.0
5       tom     17      3.8

(you can adjust the output format as desired).

Also see the comment by @Kaz. A simple loop with getchar() reading a character-at-a-time in a state loop, where you loop checking characters outputting things that are not spaces, commas or newlines, and when you hit a space or comma simply insert an output separator of your choosing and ignore all subsequent spaces, commas, etc.. until you reach your next field and start outputting characters again. Definitely worth looking at. Let me know if you have further question.

2 of 3
1

Assuming the CSV data doesn't contain quotes that protect commas, we can remove the extra spaces around commas using a program that doesn't do any buffering of the data or any sort of processing with null-terminated character arrays. We just read one character at a time using getchar, and maintain some state in the form of counters that measure how many spaces and commas we have seen:

#include <stdio.h>

int main(void)
{
  int nspc = 0;
  int ncomma = 0;
  int ch;

  while ((ch = getchar()) != EOF) {
    switch (ch) {
    case ' ': nspc++; break;
    case ',': ncomma++; break;
    default:
      if (ncomma > 0)
        while (ncomma-- > 0)
          putchar(',');
      else
        while (nspc-- > 0)
          putchar(' ');
      putchar(ch);
      nspc = 0;
      ncomma = 0;
      break;
    }
  }

  return 0;
}

Test data:

$ cat clean-comma-test 

a
aa
a,
,a
a a,
,a a
a , b
, a , b c , d
,  a , b   c d   ef,  g h
   ,
   ,a
,  ,
, ,, , ,    ,

Output:

a
aa
a,
,a
a a,
,a a
a,b
,a,b c,d
,a,b   c d   ef,g h
,
,a
,,
,,,,,,

The basic idea is:

  • if we see a field of N spaces that doesn't contain any commas, followed by a character C which isn't a space or comma, then we just reproduce N spaces and character C.

  • if we see a field of N spaces (possibly 0) containing one or more commas M, followed by a character C that isn't a space or comma, we reproduce the M commas, followed by C.

  • lines in C streams are terminated by the newline character '\n', which serves as C in the case when the comma-space field is the last item in the line.

A C program that doesn't manipulate any pointers cannot have a buffer overflow or memory leak. However, I haven't protected the counters against integer overflow. If you have a field of more than INT_MAX spaces and/or commas, the behavior is undefined. On modern systems, that's well over two billion, so there is a fair amount of justification for not caring about it.

The code also doesn't recognize other whitespace such as tabs.

🌐
YouTube
youtube.com β€Ί watch
How to remove spaces from a string in C/C++ - YouTube
In this video, I will show you how to remove spaces from a string without the need to use a second buffer ( in-place). I'm raising money to Support My Channe...
Published Β  November 7, 2016
🌐
Reddit
reddit.com β€Ί r/webdev β€Ί [javascript] how to effectively convert string to array while removing commas and the space at the beginning/end if there was any?
r/webdev on Reddit: [javascript] how to effectively convert string to array while removing commas and the space at the beginning/end if there was any?
September 14, 2021 -

i think this can be done by regEx by i don't how to look it up.

this is a learning project, but i am just thinking about the scale

i have a form where the user enter a bunch of categories and i want the user to separate those categories with a comma, but working on the case where the user add the comma but also a space after the comma (as we all do) or before the comma, how to go about treating this case, because i don't want to end up with two or three categories that are the same.

edit: i did it but i don't want to remove the post to help anyone with the same issue.

here's what i did

const categoriesAsString = e.target.value;

const categoriesTrimmed = categoriesAsString.trim();

const categoriesAsStringWithWhiteSpace = categoriesTrimmed.replace(/\s*,\s*/g,",");

const categoriesAsArray = categoriesAsStringWithWhiteSpace.split(",");

setCategories(categoriesAsArray);

🌐
freeCodeCamp
forum.freecodecamp.org β€Ί programming β€Ί javascript
Replacing space and comma from a string using regex
October 26, 2020 - I may get a string like this: 23,45,567 23,45 56 7 I want it to free of all the commas and spaces. So, I tried to use the following codes: β€œ23,45,567”.replace(β€˜/[1]$/g’, β€˜β€™) β€œ23,45,567”.replace(β€˜/[2]+$/g’, β€˜β€™) β€œ23,45,567”.replace(β€˜/^\s,$/g’, β€˜β€™) And many ...
🌐
GeeksforGeeks
geeksforgeeks.org β€Ί dsa β€Ί remove-spaces-from-a-given-string
Remove spaces from a given string - GeeksforGeeks
April 11, 2026 - Initialize n = 5 (length of the string). For i = 0, ' ' is space then shift all characters left so, string becomes "gf g" and reduce n to 4, decrement i.
🌐
ServiceNow Community
servicenow.com β€Ί community β€Ί developer-forum β€Ί need-help-to-remove-space-after-comma β€Ί m-p β€Ί 3069688
Solved: Need help to remove space after comma - ServiceNow Community
October 9, 2024 - // next test: var strVal = ' X Y, Z '; (function validateModel(inputData) { // var formattedNewVal = inputData.replace(/\s*,\s*/g, ','); var formattedNewVal = inputData.replace(/^\s+|\s+$/g, ''); gs.info('new val:'+formattedNewVal+'.'); })(strVal); results in: *** Script: new val:X Y, Z. with leading and trailing spaces removed. ... Strange Section named 'label' in sn_grc_issue form. in Developer forum yesterday Β· Client Scripts in ServiceNow in Developer forum Tuesday Β· Remove of Update and Delete Button from Custom Table in Developer forum Tuesday