Advertisement
ASP_Volume2 Miscellaneous #40861

Code Request - string replace

will replace a substrings within a string. made this for my friend. Watch out for the size of your character arrays so they have enough space for the replacements, so you dont get a buffer overflow.

AI

Résumé par IA: This codebase represents a historical implementation of the logic described in the metadata. Our preservation engine analyzes the structure to provide context for modern developers.

Code source
original-source
#include<iostream>
using namespace std;
void strreplace(char* source, char* replace, char* with);
int ifindstr(int startx,char* body,char* search);
void leftcopy(char* input,char* output,int pos);
void rightcopy(char* input,char* output,int pos);

int main()
{
	char string[255];
	strcpy(string," stuff that, this word satan evil this");
	strreplace(string,"this"," hello ");
	cout << string << endl;

	system("pause");
	return (0);
}

void strreplace(char* source, char* replace, char* with)
{
	int pos;
	pos = ifindstr(0,source,replace);
	if(pos == -1)
	{
		return;
	}
	else
	{
		char* left = new char [ strlen(source) + 1 ];
		char* right = new char [ strlen(source) + 1 ];
		leftcopy(source,left,pos);
		rightcopy(source,right,pos+strlen(replace));
		strcpy(source,left);
		strcat(source,with);
		strcat(source,right);
		delete [] left;
		delete [] right;
		strreplace(source,replace,with);
	}
}

// find string, starting from 
int ifindstr(int startx,char* body,char* search)
{
	int len = strlen(body);
	int len2 = strlen(search); // search len
	
	for(int i = startx+1; i < len; i++)
	{
		if(body[i] == search[0])
		{
			bool ichk = true;
			
			for(int z = 0; z < len2; z++)
			{
				if(body[i+z] == search[z])
				{
				}
				else
				{
					ichk = false;
				}
			}
			
			if(ichk == true)
			{
				return i;
			}
		}
	}
	
	return -1; // failure
}
// left copy
void leftcopy(char* input,char* output,int pos)
{
	int index = 0;
	for(int i = 0; i < pos; i++)
	{
		output[index] = input[i];
		index++;
	}
	output[index] = 0;
}
// right copy
void rightcopy(char* input,char* output,int pos)
{
	int index = 0;
	int len = strlen(input);
	for(int i = pos; i < len; i++)
	{
		output[index] = input[i];
		index++;
	}
	output[index] = 0;
	
}
Commentaires originaux (3)
Récupéré via Wayback Machine