![]() |
|
|
|
Thread Tools | Display Modes |
|
|
|
|
#1 |
|
Programming Guru
![]() Join Date: Apr 2005
Posts: 1,824
Rep Power: 5
![]() |
Returning An Array Of Characters
How can I return an array of characters from a function? I know there's always the option of returning a pointer, but when I try that, I'm probably doing it wrong because I have to use a for loop to reference the address of each individual pointer.
It'd be easiest to do it this way as well, so that I can just cout the function call, without needing to do anything to it. #include <iostream>
using namespace std;
// CONSTANTS
const int MAX_SIZE = 256;
int get_size(char text[MAX_SIZE])
{
for (int i=0;i<MAX_SIZE;i++)
{
if (!(text[i]))
return i;
}
return MAX_SIZE;
}
int locate(char text[MAX_SIZE], char from[MAX_SIZE],
int size_f)
{
int i2 = 0;
for (int i1 = 0;i1 < MAX_SIZE;i1++)
{
if (text[i1] == from[i2])
{
i2 ++;
if (i2 == size_f)
return i1 - size_f + 1;
}
else if (!(text[i1]))
return -1;
else
i2 = 0;
}
return -1;
}
char* replace(char text[MAX_SIZE], char to[MAX_SIZE],
int where, int size_f, int size_t)
{
char new_text[MAX_SIZE];
int offs1 = size_f+where;
int offs2 = size_t+where;
// append text before change
for (int i1=0; i1 <= where; i1++)
new_text[i1] = text[i1];
// append change
for (int i2=0; i2 <= size_t; i2++)
new_text[i2+where] = to[i2];
// append text after change
for (int i3=0; i3 <= get_size(text)-size_f-where; i3++)
new_text[i3+offs2] = text[i3+offs1];
return new_text;
}
int main()
{
char text[MAX_SIZE] = "This is some text, yaddi yaddi.";
char from[MAX_SIZE] = "some";
char to[MAX_SIZE] = "no";
int size_f = get_size(from);
int size_t = get_size(to);
int where = locate(text, from, size_f);
if (where == -1)
cout << "Value was not found anywhere inside the text";
else
cout << replace(text, to, where, size_f, size_t);
cin.sync();
cin.get();
return 0;
} |
|
|
|
| Bookmarks |