Hi.
I'm trying to remove some characters within a string and substitute
others. For instance, I want to convert:
John's new house, great ---> Johns-new-house-great
I tried with:
----------------//------------------
int main()
{
char string2[50];
char *string = "John's new house, great";
int rc = sscanf(string, "%[, ]%s", string2);
if (rc = 2)
{
printf("%s\n", string2);
}
return 0;
}
-------------//---------------
But it doesn't work. Any suggestion? Thx.
Try this:
/**********************************************************************/
/* File Id. chrsubst.c. */
/* Author: Stan Milam. */
/* Date Written: 17 Apr. 1992. */
/* Description: */
/* Implement a function to search and replace characters in a C */
/* string. */
/* (c) Copyright 2005 by Stan Milam. */
/* All rights reserved. */
/* */
/**********************************************************************/
#include <stddef.h>
#include <string.h>
/* $Revision$ */
extern char tb_copyright[];
static char *copyright = tb_copyright;
/**********************************************************************/
/* Name: */
/* chrsubst(). */
/* */
/* Description: */
/* This function will replace all occurances of one character */
/* with another in a character string. It will then return */
/* the number of substitutions. */
/* */
/* Arguments: */
/* char *s1 - String to be searched. */
/* char ch - Character to search for. */
/* char ch2 - Character to replace the value of ch. */
/* */
/* Returns: */
/* The number of times ch is in s1. */
/* */
/**********************************************************************/
size_t
chrsubst(char *s1, int ch, int ch2) {
size_t count = 0; /* The count to return */
char *wrk = strchr(s1, ch); /* Find first char in s1 */
while (wrk) { /* While we have matches */
*wrk = (char) ch2; /* Replace the character */
count++, wrk++; /* Increment the count & pointer */
wrk = strchr(wrk, ch); /* Search for next occurance */
}
return count; /* Return the count */
}
/**********************************************************************/
/* Name: */
/* substitute_char(). */
/* */
/* Description: */
/* Alias of the chrsubst() function with a more english-like */
/* name. */
/* */
/**********************************************************************/
size_t
substitute_char( char *s, int ch1, int ch2 )
{
return chrsubst( s, ch1, ch2 );
}