In: Computer Science
Answer 1:
Pseudocode substring(string inStr, int start, int size)
1. len <- inStr.length()
2. j <- 0
3. for i <- start to start+size
i. result[j] = inStr[i]
ii. j++, i++
4. result[j] <- '\0'
5. return result
Answer 2:
Code:
Code as text:
#include <iostream>
#include <string>
using namespace std;
// function to find substring of a string
string substring(string inStr, int start, int size) {
int len = inStr.length();
string result(size, ' '); // variable for result
int j = 0;
// loop from start to string size to get substr
for (int i = start; i < start + size; i++) {
result[j] = inStr[i];
j++;
}
result[j] = '\0';
return result; // return the substr
}
int main() {
cout << "Testing substring function.\n";
cout << substring("abracadabra", 3, 5) << endl;
cout << substring("asdfghjkl", 2, 6) << endl;
cout << substring("ATGCAGAAAGCTACGATCAATGATCGATC", 6, 4) << endl;
}
Sample Run:
Answer 3:
Pseudocode for search(string inStr, string s)
1. for i <- 0 till i < inStr.length()
i. subStr <- substring(inStr, i, s.length())
ii. check if subString is equal to search string
a. return index i
iii. end if
2. end for
3. return -1 i.e string not found
Answer 4:
Code:
Code as text:
#include <iostream>
#include <string>
using namespace std;
// function to find substring of a string
string substring(string inStr, int start, int size) {
int len = inStr.length();
string result(size, ' '); // variable for result
int j = 0;
// loop from start to string size to get substr
for (int i = start; i < start + size; i++) {
result[j] = inStr[i];
j++;
}
result[j] = '\0';
return result; // return the substr
}
/* function to find index of the start of the the first match of a given string protein within the string dna */
int search(string inStr, string s) {
for (int i = 0; i < inStr.length(); i++) {
string subStr = substring(inStr, i, s.length()); // get substring
// check if substring is equal to given string
if (subStr == s) {
return i; // return index if found
}
}
return -1; // return -1 if not found
}
int main() {
cout << "Testing search string function.\n";
cout << "Finding AATG in ATGCAGAAAGCTACGATCAATGATCGATC AATGGAT. \n";
int index = search("ATGCAGAAAGCTACGATCAATGATCGATC AATGGAT", "AATG");
if (index) {
cout << "Found at index: " << index;
} else {
cout << "Not found.";
}
}
Sample Run:
P.s. Ask any doubts in comments and don't forget to rate the answer