Create my own strlen and substring functions - c++

I am trying to create my own strlen and substr functions and I have 1 problem.
for example, let say I have the string ABC, my strlen will return 3, let say I want to cut this string from 0 to 1 its should return to me A,but I get some trash values, if I insert the substr to a new char and check the length I will recieve 14.
this is my code:
int len(char *w){
int count=0;
int i=0;
while (w[i]!='\0')
{
count++;
i++;
}
//cout<<"Length of word is:"<<count<<"\n";
return count;
}
char *subs(char *w,int s,int e){
int i,j;
int size=0;size=(e-s);
//cout<<"new size is:"<<size<<"\n";
char *newW=new char[size];
for(i=0,j=s;j<e;i++,j++)
{
newW[i]=w[j];
}
return newW;
}
int main(){
char* x="ABC";
//int v=len(x);
//cout<<v;
char *n=subs(x,0,1);
cout << len(n);
for(int g=0;g<len(n);g++)
//cout<<n[g];
return 0;
}
I would like to get some comments what I did wrong, Thanks!

Change your condition loop for for(i = 0, j = s ; j < e && w[j] != '\0'; i++, j++) and you need to allocate size +1 since you have to add a \0 at the end of the string.

sub string should end with a '\0', the array size should add one. Here is the code:
char *subs(char *w,int s,int e){
int i,j;
int size=0;size=(e-s);
//cout<<"new size is:"<<size<<"\n";
char *newW=new char[size + 1];
for(i=0,j=s;j<e;i++,j++)
{
newW[i]=w[j];
}
newW[i] = '\0';
return newW;
}

Related

function to return the position of a value in an array (C++, Splashkit)

So I have designed an array where the user enters in five names, and the terminal will print those names and identify the longest name. I'm now trying to introduce a function where the user enters a name, and if that name is in the array, to print the position of that name (if the name is not there, print -1). I'm using the Splashkit library which is a little different. I've tried a few different variations but no luck so far. This is what I have...
int index_of(string value, string names[], int size)
{
value = read_string("Enter name to find index: ");
for(int i = 0; i < size; i++)
{
if ((names[i]) == string(value))
{
return i;
write_line("The index is: ");
write(i);
}
}
return -1;
}
It compiles fine but just won't work, even when I call it in main. Does anyone have any ideas? Thanks :)
int main()
{
#define SIZE 5
string names[SIZE];
int i;
i = 0;
while( i < SIZE )
{
names[i] = read_string("Enter a name:");
i++;
}
for(i = 0; i < SIZE; i++)
{
write_line(names[i]);
}
int total;
total = total_length(names, SIZE);
write("Total length: ");
write_line(total);
bool has_connor;
has_connor = contains(names, SIZE, "connor");
if ( has_connor ) write_line("contains Connor");
write("The longest name is: ");
write_line(longest_name(names, SIZE));
int index_of(int value, string names[], int size);
return 0;
}
I think that these lines write_line("The index is: "); write(i); are useless because return comes before them. try
write_line("The index is: ");
write(i);
return i;

How to insert a string at x position in another string?

I have to use a function that takes two strings and one integer value that tell the position at which the second string is to be entered in the first.
For Example:
String 1 = "I have apple"
String 2 = "an "
position = 6,
Output:
String 1 = "I have an apple"
Here's my code, so far:
#include <iostream>
using namespace std;
const int SIZE=102;
void insertString(char str1[ ],char str2[ ],int position);
int main()
{
char str1[SIZE], str2[SIZE];
int position,i=0,j=0;
cout<<"Enter string 1 of atmost 50 characters:\n";
cin.getline(str1,SIZE/2);
cout<<"Enter string 2 of atmost 50 characters:\n";
cin.getline(str2,SIZE/2);
cout<<"Enter Position number where String 2 is to be inserted: ";
cin>>position;
while(position<0||position>50)
{
cout<<"Invalid input. Enter a positive Position number less than 51\n"<<
"where String 2 is to be inserted: ";
cin>>position;
}
insertString(str1,str2,position);
cout<<"Modified string 1: "<<str1<<endl;
system("pause");
return 0;
}
/******************************************************************************
Definition of function insertString:
This function takes two C-string in form of character arrays and one integer value
as parameters
It inserts String 2 in String 1 on the required position.
*******************************************************************************/
void insertString(char str1[ ],char str2[ ],int position)
{
char temp[SIZE];
int i,j,countStr2;
for(j=0;j<SIZE&&str2[j]!=0;j++)
countStr2=j;
for(i=position,j=0;i<SIZE,j<=countStr2; i++,j++)
{
temp[i]=str1[i];
str1[i]=str2[j];
}
}
This logic overwrites some characters of string 1. What should I do?
Any help will be appreciated.
#include<cstring>
#include <iostream>
/*The following function supposes that str1 and str2 are cString (i.e)
ended by `\0` and inserts str2 in str1 at the specified position in a
newStr, then returns the new string as apointer*/
char* insertString(const char str1[ ],const char str2[ ],const int& position)
{
int shiftedPos=position-1;
int str2Size=strlen(str2);
int str1Size=strlen(str1);
int newSize=str2Size+str1Size+1;
char* newStr=new char[newSize];
for(int i=0; i<shiftedPos; i++) newStr[i]=str1[i];
for(int i=0; i<str2Size; i++) newStr[shiftedPos+i]=str2[i];
for(int i=0; i<newSize; i++) newStr[shiftedPos+str2Size+i]=str1[shiftedPos+i];
newStr[newSize]='\0';
return newStr;
}
int main(){
auto str1 = "I have apple";
auto str2 = "an ";
std::cout<<insertString(str1,str2, 8);
return 0;
}
Another code to perform exactly as you wanted
#include<iostream>
#include<cstring>
/*The following function supposes that str1 and str2 are cString (i.e)
ended by `\0` and that the memory allocated by str1 >= the len(str1)+len(str2)+1.
It inserts str2 in str1 at the specified position in str1*/
void insertString(char str1[ ], char str2[ ], int position)
{
int str1Size=strlen(str1);
int str2Size=strlen(str2);
int newSize=str2Size+str1Size+1;
int cppPosition=position-1;
for(int i=str1Size; i>=cppPosition; i--) str1[i+str2Size]=str1[i];
for(int i=0; i<str2Size; i++) str1[cppPosition+i]=str2[i];
str1[newSize]='\0';
}
int main(){
char str1[50]= "I have apple";
char str2[50] = "an ";
insertString(str1,str2, 8);
std::cout<<str1;
return 0;
}
If you have to implement the void insertString(char str1[ ],char str2[ ],int position) function, you don't have many options here.
One of the possible solutions is to shift the characters in the first string to the right to make space for the second string to be inserted there.
Such an approach might look like this:
void insertString(char str1[], char str2[], int position) {
const int len1 = strlen(str1);
const int len2 = strlen(str2);
// First, shift all the characters from the given position to the right by `len2` positions:
for (int i = 0; i < len1 - position; ++i) {
str1[len1 - i - 1 + len2] = str1[len1 - i - 1];
}
// Then insert the second string in the given position:
for (int i = 0; i < len2; ++i) {
str1[position + i] = str2[i];
}
// Make sure to create a new terminator since the
// previous one got overwritten by the the first loop
str1[len1 + len2 + 1] = 0;
}
LIVE DEMO
Note, that this is potentially insecure! If there is not enough space in the str1 array to store another strlen(str2) characters, it will lead to a buffer overflow.
Way more secure option would be to allocate a new buffer for your new concatenated string on the heap, but for the sake of your assignment, this should suffice.
Since you're using C++, you should avoid this approach altogether in any production code, replacing char arrays with std::string, for example. But I've already read in the comments that you can't use it just yet.
Assuming you can use <string>, then I would put std::string::substr to use:
#include <string>
std::string originalString = "I have apple"; // original string
std::string insert = " an "; // added space beforehand for the new word to be inserted
int position = 6; // index where the new word would be inserted
int remainingStringSize = originalString.length() - position - 1; // count how many characters remain from the position you're inserting
std::string combinedString = originalString.substr(0, 6) + insert + originalString.substr(position +1, remainingStringSize); // resulting combined string
Words of caution, you obviously would need to check the following:
That index position is within the length of the original string where you wish to insert
That the remaining # of characters is more than 0

C++ Char Array Find / Replace a char

So basically I have an array which looks like this:
char array[25];
I have an 'X' put in there, and 24 'O's. I am trying to create a function where I can find the location of 'X' in the array, so then I can move it whenever a control is typed in. Here is some code to get an idea on what I am thinking, I just can't put it together.
int findX(){
//make this find the location of X out of the 25 char array.
//then return the slot of X as a number, like if it's in the 20th slot, then it will return 20 ?
//return(locationOfX);
}
for(int i = 0; i <= array.Length; i++)
{
if(array[i] == 'X')
{
return i;
}
}
This should do it, I had no chance testing it, but it should work
I think Ron's answer is more correct because actually I think in C there isn't a function like "XXX.length()", so you need to pass the length of the array to the function.
Pass in the array and the number of elements.
1. The manual approach:
int findX(char arr[], int count){
for (int i = 0; i < count; i++){
if (arr[i] == 'X'){
return i;
}
}
return -1;
}
2. Use std::find function:
int findX2(char arr[], int count){
return std::find(arr, arr + count, 'X') - arr;
}
Slight twist with the std::distance function:
int findX2(char arr[], int count){
return std::distance(arr, std::find(arr, arr + count, 'X'));
}
3. Pass in the beginning and the end of the array:
int findX3(char* arrbegin, char* arrend){
return std::distance(arrbegin, std::find(arrbegin, arrend, 'X'));
}
and use like:
std::cout << findX3(std::begin(arr), std::end(arr));
4. Template function left as an exercise.
That being said, prefer std::vector or std::array to raw arrays.
In language C you can use strstr function.
#include "string.h"
int findX(char array[])
{
char *result = strstr(array, "s");
return result - array;
}
int main()
{
char array[25];
int index = findX(array);
}
in C++ use std::find() or just change array to std::string and use string::find
here is the code:
#include <string>
int main()
{
std::string array = "oooooooooosoooooooooooooo";
int index = array.find("s");
return 0;
}

I want to return the array index, not the array value

Homework question that I can't figure out. Not even gonna lie. It's suppose to return the array index where my function finds the character it's searching for or return -1 if it doesn't find the character. Instead it returns the value stored in the arrays element. i.e. I type "This is my string" it should return 8 but instead it returns 109(ASCII code of M).
int search(const std::string &array, char character) {
for (int i = 0; i < array.length(); i++) {
if (i = character) {
return i;
}
return -1;
}
}
I'm taking a break from homework for the day, but any advice would be appreciated. Maybe I'll see the problem tomorrow with fresh eyes.
int search(const std::string &array, char character) {
for (int i = 0; i < array.length(); i++) {
if (i **==**character) {
return i;
}
return -1;
}
}
In your loop, i = character is not a comparison, it's an assignement. In c++, the comparison operator is == .
On a side note, you could replace your whole function by the function find()
EDIT
What I failed to see is that your if is wrong AND your for too.
Here is a working piece of code :
#include<string>
#include<iostream>
int search(const std::string &array, char character) {
for (int i = 0; i < array.length(); i++) {
if (array[i] == character) {
return i;
}
}
return -1;
}
int main(){
std::string meh = "meh";
std::cout << search(meh,'e') << std::endl;
}
First error, you have to compare the element of the array with character, not the counter (i).
Second error, you're returning -1 if you if failed in your for. But if the character is not the first character in the string, it will fail.
Thanks #quentin for having me take a second look.
std::string::find() returns exactly what you want:
std::size_t search(const std::string& array, char character)
{
return array.find(character); // if 'character' is not found returns std::string::npos
}
And if you don't want to use it:
std::size_t search(const std::string& array, char character)
{
for(std::size_t i=0; i<array.size(); ++i)
if(array[i]==character) return i;
return -1;
}
#include <iostream>
int search(const std::string &array, char character);
int main () {
const std::string string1 = "daidalos";
std::cout << search(string1, 'i');
return 0;
}
int search(const std::string &array, char character) {
for (int i = 0; i < array.length(); i++) {
if (array[i] == character) {
return i+1;
}
}
return -1;
}
Output:
3 means 3rd place (true).However, if you want to return multiple indexes of the string, you can use an std::pair or std::tupple.
Excatly what I was looking for.
#include<string>
#include<iostream>
int search(const std::string &array, char character) {
for (int i = 0; i < array.length(); i++) {
if (array[i] == character) {
return i;
}
}
return -1;
}

Remove chars and append them in the end of the string ( C++ )

How can I erase the first N-th characters in a given string and append them in the end. For example if we have
abracadabra
and we shift the first 4 characters to the end then we should get
cadabraabra
Instead of earsing them from the front which is expensive there is another way. We can rotate them in place which is a single O(N) operation. In this case you want to rotate to the left so we would use
std::string text = "abracadabra";
std::rotate(text.begin(), text.begin() + N, text.end());
In the above example if N is 4 then you get
cadabraabra
Live Example
You can try an old-fashioned double loop, one char at a time.
#include "string.h"
#include "stdio.h"
int main() {
char ex_string[] = "abracadabra";
int pos = 4;
char a;
int i, j;
size_t length = strlen(ex_string);
for (j = 0; j < pos; j++) {
a = ex_string[0];
for (i = 0; i < length - 1; i++) {
ex_string[i] = ex_string[i + 1];
}
ex_string[length-1]=a;
}
printf("%s", ex_string);
}
string str = "abracadabra" //lets say
int n;
cin>>n;
string temp;
str.cpy(temp,0,n-1);
str.earse(str.begin(),str.begin()+n-1);
str+=temp;
Reference
string::erase
string::copy
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string str;
cin >> str;
int number;
cin >> number;
string erasedString = str;
string remainingString = str.substr(number + 1, strlen(str));
erasedString.erase(0, number);
return 0;
}