In: Computer Science
I have a char memory[1024]. I want to write the string "mike" into the memory starting from an index. I also need a function to move "mike" to another index in the same memory swapping m and k in mike. Basically, i need a function to write to memory and a function to move the string to an index. Thank you
In c++ please.
If this answer doesn't meet your requirements, then please
comment and let me know, so that I can help you.
Please look at my code and in case of indentation issues check the screenshots.
---------main.cpp---------------
#include <iostream>
#include <string.h>
using namespace std;
//this function intializes the memory with _, you can choose to
intialize it with any letter you want.
void initialize_memory(char memory[], int size)
{
for(int i = 0; i < size; i++){
memory[i] = '_';
}
}
void writeString(char memory[], int size, int index, char
*str)
{
for(int i = 0; i < strlen(str); i++)
//writes the string at the specified index
{
if(index < size){
memory[index] =
str[i]; //copies each character one by one
index++;
}
}
}
void moveString(char memory[], int size, int oldindex, int
newindex)
{
int i = oldindex;
char temp[size];
//temporary array to read the string and store its copy
int j = 0;
while(memory[i] != '\0'){
temp[j] = memory[i];
//copy each character of the old string from the memory
i++;
j++;
}
temp[j] = '\0';
//terminate the string with null character, to
denote the end of string
initialize_memory(memory, size);
//reinitialize memory
writeString(memory, size, newindex, temp);
//write the string at newindex, the string is in temp array
}
int main()
{
int size = 1024;
char memory[size]; //declare a character
array memory of size 1024
initialize_memory(memory, size);
//initialize the memory with _ at every index
int index;
cout << "At which index do you want to write the
string: "; //ask the user where they
want to write the string in memory
cin >> index;
writeString(memory, size, index, (char
*)"mike"); //write the string at the memory specified
by the user
cout << "Memory:\n" << memory <<
endl;
//print the memory array
int oldindex = index; //store the
location of the index, where we wrote the string
int newindex;
cout << "\nAt which index do you want to move
the string: "; //ask the user another index, where they want to
move the string
cin >> newindex;
moveString(memory, size, oldindex,
newindex); //move the string the location specified by
the user
cout << "Memory:\n" << memory <<
endl;
//print the memory array
return 0;
}
----------Screenshots--------------
----------Output--------------
------------------------------------
Please give a thumbs up if you find this answer helpful.
If it doesn't help, please comment before giving a thumbs
down.
Please Do comment if you need any clarification.
I will surely help you.
Thankyou