I got the char array "anana" and I am trying to get a "B" into the beginning in the char array so it spells "Banana" but I cannot wrap my head around how to construct a simple while loop to insert the B and then move every letter one step to the right
-
1Copy it to another array.Eugene Sh.– Eugene Sh.2018-03-12 18:10:05 +00:00Commented Mar 12, 2018 at 18:10
-
Can you use a temporary array? Or does it have to be done in-place using the original array?Some programmer dude– Some programmer dude2018-03-12 18:12:00 +00:00Commented Mar 12, 2018 at 18:12
-
Wow I cannot believe I didn't come up with that earlier! ThanksJ. Doe– J. Doe2018-03-12 18:12:58 +00:00Commented Mar 12, 2018 at 18:12
-
I will copy it to another array and then write every letter the same but one step to the rightJ. Doe– J. Doe2018-03-12 18:13:35 +00:00Commented Mar 12, 2018 at 18:13
-
If you're stuck doing it in-place, move the "anana" over by copying from right-to-left (or just use memmove(), which does that for you).Lee Daniel Crocker– Lee Daniel Crocker2018-03-12 18:20:58 +00:00Commented Mar 12, 2018 at 18:20
|
Show 1 more comment
3 Answers
You can use a more traditional approach using...
#include <stdio.h>
int main()
{
char s[] = "ananas";
char b[7] = "B";
for(int i = 0; i < 7; ) {
char temp = s[i++];
b[i] = temp;
}
printf("%s", b);
return 0;
}
3 Comments
Eat at Joes
You can't dynamically resize an array in C since the memory has to be contiguous. Hence the reason for two arrays in the above answer. As for your code I recommend you ask a specific question on SO.
Rishav
Okay what if i dont care about the last character and just want to shift the remaining characters to the right and add a new character in the beginning. Then am I allowed to do it? Coz im not resizing the array but just altering the array's contents.
Please follow these steps:
- Create a new array of size 7 (Banana + terminator). You may do this dynamically by finding the size of the input string using
strlen(). - Place your desired character say 'B' at
newArray[0]. - Loop over
i=1 -> 7 - Copy values as
newArray[i] = oldArray[i-1];
1 Comment
Some programmer dude
Don't forget the terminator character! The string
"Banana" is seven characters including it.