How to add characters to an array

So I am currently working on a program that needs to add 'ly' to the end of an array of characters if it does not have it. Except I do not know how to write the code to recognize if the last of the array already has and 'ly' and I do not know what to put in to add the characters of 'ly'. If anyone could help, it would be greatly appreciated!
It depends on the type of string. If it's an STL string, there's a find method that'll return the position. If it's a C string, there's strstr() that returns the position. You then have to work out if that position is two from the end.
If you are using a standard array of chars in C this might work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int main ()
{
	const int size = 6;
	char arr[size] = {'a', 'b', 'c', 'l' , 'y', '\0'};
	string tmp;
	string key = "ly";  // C++ way. includes the null terminator

    for (int i = size - (key.size()+1); i < size-1 ; i++)
    	if (i > 0 && i < size-1) 
            tmp += arr[i]; 

	if (tmp == key)
		cout << "yes";
	else
		cout << "no";
	
	return 0;
}


Notice that I included the null terminator on the end of the chart array. You should do this so you can use C library fucntions like the one kbw suggested. They rely on the null terminator being present.


Adding characters can be dangerous if using an array chars. Just make sure you are not accessing anything over (size-1) and you will be alright.

Personally I would make this a class method that would add the letters automatically. Actually I'd make it so that it will add any number of letters given they are less than or equal to the size of the array to the end of the array to make it more flexible. This code accomplishes most of that but does not check for everything.

P.S. - I hate using strings in C. I might as well be writing in assembly. lol
Last edited on
Okay this helps me out greatly, except would it work if i prompted the user to put a period after the word or some sort of punctuation and then just removed that?
Sure, why not?

You don't even need to use this, I just was thinking how to be a flexible as possible. To be honest it looks messy and should be encapsulated in a class somewhere. If you want to have them use punctuation then that's fine but if you want to discount said punctuation in terms of finding the last true letters then you need to account for it in your starting index, ie - for (int i = size - (key.size()+1); i < size-1 ; i++)

Last edited on
Topic archived. No new replies allowed.