473,802 Members | 1,937 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

string function

How can I replace an occurence of p(a string) in an other string(s) with
np(new string)..
char* replace _pattern(char *s,char *p,char *np)
PLEASE HELP ME!!!!!

Nov 14 '05 #1
13 2370
"dimitris67 " <xi******@hol.g r> wrote:
# How can I replace an occurence of p(a string) in an other string(s) with
# np(new string)..
# char* replace _pattern(char *s,char *p,char *np)
# PLEASE HELP ME!!!!!

Nothing in the C library. One way to implement it is to build up a new string.
Use ststr to search for p in s. Copy characters from s to where strstr found
a match to the new string, copy np to the new string, and then advance p
past the found substring. Continue searching with strstr through the rest of
s. When strstr finds nothing, copy the remaining, unmatched portion of s to
the new string.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
Title does not dictate behaviour.
Nov 14 '05 #2
dimitris67 wrote:
How can I replace an occurence of p(a string) in an other string(s) with
np(new string)..
char* replace _pattern(char *s,char *p,char *np)
PLEASE HELP ME!!!!!


its is quite easy, use fast kmp (knuth-morris-pratt) algorithm for searching
all occurrences of pattern1 in string and next create new string with
pattern2 (kmp returns offsets to pat1 in string so you can replace pat1
with pat2).

--
---------------------------------------------
www.cepa.one.pl
FreeBSD r0xi qrde ;-]
Nov 14 '05 #3
use strstr so that it gives the first occurence of the string s2 in
string s1 and then copy the replacing string .

as every body knows

while(*s2++=*s1 ++);

do the operation of strcpy

check it out

Nov 14 '05 #4
dimitris67 wrote:
How can I replace an occurence of p(a string) in an other string(s) with
np(new string)..
char* replace _pattern (char *s, const char *p, const char *np)


There are three distinct cases. |p| < |np|, |p| == |np|, |p| > |np|.

So your first step is to determine which of those three cases you are
in, and then perform the operation with custom code for each.

The |p| == |np| is trivial. Just search for occurrences of p, and
directly overwrite it with |np|.

The case where |p| > |np| is also fairly straightfoward. You have a
read pointer and write pointer, both of which are initialized to each
other. You copy and increment step by step, except when you notice an
occurrence of p. Then you copy over np in its place, then increment
the write pointer by |np|, and the read pointer by |p| and continue in
a loop.

The case where |p| < |np| is the really tricky one because you have to
perform an insert as you go, but you can't tell the amount of total
inserting you will need to do until you have completely scanned the
string. So the easiest way to do it, is to do it in two passes. In
the first pass you simply count up the number of occurrences of p, and
compute len, the length of p. You then compute the amount that the
string grows (len * (|np| - |p|)) and in a second pass going backwards
from the end you copy the string in segment chunks until you encounter
p, then you overwrite it with np, etc.

If you want to see an example of a very similar look at the function
bFindAndReplace () in "The Better String Library":

http://bstring.sf.net/

---
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/

Nov 14 '05 #5
In article <11************ **********@g49g 2000cwa.googleg roups.com>,
<we******@gmail .com> wrote:

dimitris67 wrote:
How can I replace an occurence of p(a string) in an other string(s) with
np(new string)..
char* replace _pattern (char *s, const char *p, const char *np)


There are three distinct cases. |p| < |np|, |p| == |np|, |p| > |np|.


You had me at |p| < |np|
--
7842++
Nov 14 '05 #6
In article <11************ **********@g49g 2000cwa.googleg roups.com>,
<we******@gmail .com> wrote:
There are three distinct cases. |p| < |np|, |p| == |np|, |p| > |np|.


Travelling Salesmen worldwide are still arguing about whether
|p| == |np|
(Sorry, a little mathematics humour there...)
--
Would you buy a used bit from this man??
Nov 14 '05 #7
we******@gmail. com wrote:
dimitris67 wrote:
How can I replace an occurence of p(a string) in an other string(s) with
np(new string)..
char* replace _pattern (char *s, const char *p, const char *np)

There are three distinct cases. |p| < |np|, |p| == |np|, |p| > |np|.

So your first step is to determine which of those three cases you are
in, and then perform the operation with custom code for each.

The |p| == |np| is trivial. Just search for occurrences of p, and
directly overwrite it with |np|.

The case where |p| > |np| is also fairly straightfoward. You have a
read pointer and write pointer, both of which are initialized to each
other. You copy and increment step by step, except when you notice an
occurrence of p. Then you copy over np in its place, then increment
the write pointer by |np|, and the read pointer by |p| and continue in
a loop.

The case where |p| < |np| is the really tricky one because you have to
perform an insert as you go, but you can't tell the amount of total
inserting you will need to do until you have completely scanned the
string. So the easiest way to do it, is to do it in two passes. In
the first pass you simply count up the number of occurrences of p, and
compute len, the length of p. You then compute the amount that the
string grows (len * (|np| - |p|)) and in a second pass going backwards
from the end you copy the string in segment chunks until you encounter
p, then you overwrite it with np, etc.

If you want to see an example of a very similar look at the function
bFindAndReplace () in "The Better String Library":

http://bstring.sf.net/

---
Paul Hsieh
http://www.pobox.com/~qed/

You make things too complicated.

/*************** *************** *************** *************** **********/
/* File Name: replace.c. */
/* Author: Stan Milam. */
/* Date Written: 13-Jan-2003. */
/* Description: */
/* Implement a function replace all occurances of a pattern. */
/* */
/* (c) Copyright 2005 by Stan Milam. */
/* All rights reserved. */
/* */
/*************** *************** *************** *************** **********/

#include <errno.h>
#include <string.h>
#include <stddef.h>

*************** *************** *************** *************** **********/
/* Name: */
/* replace(). */
/* */
/* Synopsis: */
/* #include "strtools.h " */
/* char *replace(char *target, const char *from, char *to */
/* */
/* Description: */
/* The replace function will replace all instances of the from */
/* pattern with that of the to pattern. If the to pattern is */
/* an empty string or NULL all instances of the from pattern will */
/* be removed from the target string. */
/* */
/* Note: */
/* Since a replacement pattern can be longer the the original */
/* pattern the programmer must allow for enough memory to */
/* accomodate a larger target string to allow successful */
/* completion of the operation. */
/* */
/* Arguments: */
/* char *target - The string in which patterns will be */
/* replaced. Cannot be NULL */
/* */
/* const char *from - The pattern to be replaced. Cannot be NULL */
/* or an empty string (i.e. ""). */
/* */
/* const char *to - The replacement pattern. Using a NULL */
/* pointer will be interpreted the same as an */
/* empty string (i.e. ""). */
/* */
/* Return Value: */
/* In all cases the address of the target string. Should either */
/* the target string or the from pattern be NULL the global errno */
/* variable will be set to EINVAL. */
/* */
/*************** *************** *************** *************** **********/

char *
replace ( char *p_target, const char *p_from, const char *p_to )
{
size_t to_len, from_len;
char *l_to, *ptr, *rv = p_target;

/*************** *************** *************** *************** ******/
/* Check for excrement passed in as arguments! */
/*************** *************** *************** *************** ******/

if ( p_target == NULL || p_from == NULL || *p_from == '\0' )
errno = EINVAL;
else {

/*************** *************** *************** *************** **/
/* I should not have to do this but some compilers complain */
/* when I try to assign the empty pointer to p_to. p_to */
/* points to a string of const characters. I should be able */
/* to change the pointer! */
/*************** *************** *************** *************** **/

l_to = p_to == NULL ? "" : (char *) p_to;

/*************** *************** *************** *************** **/
/* Get the lengths before we enter the loop. */
/*************** *************** *************** *************** **/

to_len = strlen( l_to );
from_len = strlen( p_from );

for(ptr = strstr(p_target ,p_from); ptr; ptr = strstr(ptr,
p_from)) {

/*************** *************** *************** *************/
/* We must either shrink out the replaced pattern or make */
/* room for the new pattern. If the two patterns are of */
/* equal length we don't care. */
/*************** *************** *************** *************/

if ( to_len != from_len )
memmove(ptr + to_len,ptr + from_len,strlen (ptr +
from_len)+1);

/*************** *************** *************** *************/
/* Once everthing is adjusted all we have to do is */
/* replace :-). */
/*************** *************** *************** *************/

memmove( ptr, l_to, to_len );

/*************** *************** *************** *************/
/* Bump the pointer by the length of the replacement */
/* pattern just to be safe. */
/*************** *************** *************** *************/

ptr += to_len;
}
}
return rv;
}

Regards,
Stan Milam.

Nov 14 '05 #8
ro******@ibd.nr c-cnrc.gc.ca (Walter Roberson) wrote:
In article <11************ **********@g49g 2000cwa.googleg roups.com>,
<we******@gmail .com> wrote:
There are three distinct cases. |p| < |np|, |p| == |np|, |p| > |np|.


Travelling Salesmen worldwide are still arguing about whether
|p| == |np|

(Sorry, a little mathematics humour there...)


That's not just mathematics, that's perfectly good computing science.

Richard
Nov 14 '05 #9

"dimitris67 " <xi******@hol.g r> wrote in message
news:4a******** *************** *******@localho st.talkaboutpro gramming.com...
How can I replace an occurence of p(a string) in an other string(s) with
np(new string)..
char* replace _pattern(char *s,char *p,char *np)
PLEASE HELP ME!!!!!


char *replace_patter n(char *s, char *p, char *np)
{
char *sub;

/* find pattern */
sub = strstr(s, p);
if(!sub)
{
/* pattern not found */
return 0;
}
answer = malloc( strlen(s) - strlen(p) + strlen(np) + 1);
/* out of memory. */
if(!answer)
return 0;

/* copy the leading characters */
strncpy(answer, s, sub - s);
/* evil strncpy appends no null */
answer[sub-s] = 0;
/* add the repalcement pattern */
strcat(answer, np);
/* add the trailing characters */
strcat(answer, sub + strlen(p));

return answer;
}

If you want to replace all the occurences, call iteratively until the
function returns a null. This is not very efficient and will fail if the
replacement contains the search pattern, but removing these restrictions
makes the whole thing a lot more complex.
Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
3699
by: Derek Hart | last post by:
I wish to execute code from a string. The string will have a function name, which will return a string: Dim a as string a = "MyFunctionName(param1, param2)" I have seen a ton of people discuss how reflection does this, but I cannot find the syntax to do this. I have tried several code example off of gotdotnet and other articles. Can somebody please show me the code to do this?
9
5716
by: Danny | last post by:
HI again Is there a nifty function in access that will: 1. return the amount of occurances of a small string within a larger string? this<br>is<br>a<br>test would return 3 for <br>
4
5401
by: songkv | last post by:
Hi, I am trying to reassign an array of char to a string literal by calling a function. In the function I use pointer-to-pointer since I want to reassign the "string array pointer" to the string literal. But the second printf seems to give me garbage. Any advise on what I am doing wrong? Thanx
4
8829
by: Simon Schaap | last post by:
Hello, I have encountered a strange problem and I hope you can help me to understand it. What I want to do is to pass an array of chars to a function that will split it up (on every location where a * occurs in the string). This split function should allocate a 2D array of chars and put the split results in different rows. The listing below shows how I started to work on this. To keep the program simple and help focus the program the...
18
2448
by: intercom5 | last post by:
I'm writing a program in C, and thus have to use C strings. The problem that I am having is I don't know how to reallocate the space for a C string outside the scope of that string. For example: int main(void) { char *string1; string1 = malloc(6); sprintf(string1, "Hello");
35
2588
by: Cor | last post by:
Hallo, I have promised Jay B yesterday to do some tests. The subject was a string evaluation that Jon had send in. Jay B was in doubt what was better because there was a discussion in the C# newsgroup on 25 September. The regular expressions where in that newsgroup too involved. I told yesterday night, to Jay that I would test all 4 methods and the stupid method I was thinking of the first time that night when I saw Jon's
5
2620
by: Sia Jai Sung | last post by:
Hi, I have a class that I modify from a sample program, like below ========================================== Imports System Imports System.Web.UI Imports System.Security.Cryptography public Class CSoccerichCommonFunc
9
7136
by: rsine | last post by:
I have developed a program that sends a command through the serial port to our business system and then reads from the buffer looking for a number. Everything worked great on my WinXP system, but when I tried the program on the Win98 system it will be running on, I get the following error: Cast from string "2076719" to type 'Long' is not valid I am not sure why I only get this error on the Win98 system or how to go about correcting...
17
8156
by: Tom | last post by:
Is there such a thing as a CONTAINS for a string variable in VB.NET? For instance, I want to do something like the following: If strTest Contains ("A","B", "C") Then Debug.WriteLine("Found characters") Else Debug.WriteLine("Did NOT find characters!") End If
11
5360
by: Darren Anderson | last post by:
I have a function that I've tried using in an if then statement and I've found that no matter how much reworking I do with the code, the expected result is incorrect. the code: If Not (strIn.Substring(410, 10).Trim = "") Then 'Something processed Else 'Something processed
0
9699
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10538
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10285
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10063
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6838
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5494
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5622
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4270
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2966
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.