Remove chars and append them in the end of the string ( C++ ) - 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;
}

Related

Find and output longest string word c++

I'm pretty new to programming and recently started working with strings. In my mind, this idea should somewhat work, but I have no idea what's wrong.
So I go through the string, with simb++ (to find length of the word) and where++ (to find where in the string am I) until I find a space, where I compare with the longest word I've found so so far (temp) and if it's longer, I make it the longest and find starting point of the word (start). When the for(...) ends, I write the word in the last for()
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence;
string longest="";
int simb=0;
int temp=0;
int where=0;
int start=0;
cout<<"Input sentence"<<endl;
getline(cin,sentence);
for(int i=0 ; i<sentence.size() ; i++)
{
if(sentence[i]!=' ')
{
simb++;
where++;
}
if(sentence[i]==' ')
{
if(simb>temp)
{
where++;
simb++;
start=where-simb;
temp=simb;
}
simb=0;
}
}
for(int m=start ; m<=temp ; m++)
{
longest=longest+sentence[m];
}
cout<<"longest sentence"<<longest<<endl;
return 0;
}
There are a number of issues in your code:
if simb<=temp you don't increment where, you can just remove where completely and use i instead.
incrementing simb before calculating start results in start being 1 less than it should be
you don't check the length of last word in the string (assuming the string doesn't end with whitespace)
your final for loop goes from start to temp but should go from start to start + temp
Fixing these issues gives:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string sentence;
int simb = 0;
int temp = 0;
int start = 0;
string sentence = "test test2 test 3 test 4 foo longest";
for (int i = 0; i <= sentence.size(); i++)
{
if (i != sentence.size() && sentence[i] != ' ')
{
simb++;
}
else
{
if (simb > temp)
{
start = i - simb;
temp = simb;
}
simb = 0;
}
}
string longest = "";
for (int m = start; m < start + temp; m++)
{
longest = longest + sentence[m];
}
cout << "longest sentence: '" << longest << "'\n";
return 0;
}
Note that using std::istringstream would be much simpler:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string sentence = "test test2 test 3 test 4 foo longest";
std::string longest;
std::stringstream ss(sentence);
std::string word;
while (ss >> word)
{
if (word.length() > longest.length())
{
longest = word;
}
}
std::cout << "longest sentence: '" << longest << "'\n";
return 0;
}
You can try this:
1.first locate where the spaces are.
2.calculate the gap between the two consequent words/strings.
3.find the word which has the maximum gap.
4.the world which has the maximum gap will be the longest one.
It's not c++ specific you can try this with any language.
Here is the c++ example:
#include <iostream>
#include <string>
using namespace std;
int main(){
//to get the user input
cout<<"Enter a sentence:"<<endl;
string s;
getline(cin,s);
// here the old value refers to the last index having space
// gap is the difference betweeen latest index having space and the old value
// max stores the maximum gap
int old=0;
int max=0;
int gap=0;
//these two values store the starting and ending index of longest string
int startIndex;
int endIndex;
// This for loop determines the maximum gap and calculates the starting
// and ending index of the longest word.
for(int i=0;i<s.size();i++){
if(isspace(s[i])|| i==s.size()){
if((i-old)>gap){
max=(i-old);
startIndex=i-max;
endIndex=i;}
gap=(i-old);
old=i+1;}
}
cout<<"longest string in the sentence is:";
//here we are using the determined starting and ending indices to print the longest word
for(int i=startIndex;i<=endIndex;i++){
cout<<s[i];
}
return 0;
}

Reversing characters from input

I am trying to reverse a char which has been provided in input from an user. I am having issues with the reverse function, particularly the loop. I can't get it to work- can I get advice?
#include <iostream>
using namespace std;
#include <cstring>
char* reverse(char* input) {
int len = strlen(input);
char temp[len];
for(int i=len; i>len; --i) {
temp[i]+=input[i];
}
return temp;
}
int main()
{
char input[100];
while(cin>>input) {
cout << reverse(input);
}
return 0;
}
Your Program has few issues
You're trying to return local variable address i.e. temp array address. The Function will return the address to main function. Since memory might get cleaned so it will print garbage value present at the address.
As Rohan Bari mentioned variable length array might cause undefined behavior. There for you can create a constant length array i.e.
char temp[100];
or you can dynamically allocate array on heap. Memory allocated on heap do not get cleared after termination of block but we have to manually delete it.
char* temp = new char[len];
As array start from 0 it goes till len-1 so loop condition should start from len-1 and has to go till 0 to reverse.
+ operator do not work's with array or char even if you are trying to add just char it preforms normal integer addition of their ASCII value.
Here is improved version of your code
#include<iostream>
using namespace std;
#include <cstring>
char* reverse(char* input) {
int len = strlen(input);
char* temp = new char [len]; // or you can use char temp[100];
int j = 0; //temp variable to enter values from 0th index if we use same as loop it just enter in the same order as original char array.
for(int i=len-1; i>=0; --i) {
temp[j++] = input[i];
}
temp[j] = '\0';
return temp;
}
You have got several errors in the program.
The variable-length arrays are used here:
char temp[len];
This should not be applied in C++ since this invokes undefined-behavior. Note that this is a valid statement in the C99 standard.
There is a better alternative to this. That is to take the std::string built-in type in use.
In the following line:
temp[i] += input[i];
You are not sequentially adding one character after another, but the values of them in a single integer. This could be not a problem if temp was of the type std::string.
The reverse function should look like this:
const char *reverse(char *input) {
int len = strlen(input);
std::string temp;
while (len--)
temp += input[len];
return temp.c_str();
}
len should actually be (len-1) and i should be >= 0 not len, so from (len-1) to 0 your loop should run.
for(int i = len-1; i >= 0; i--){}
You have to allocate the new array with the new keyword if you don't want to use a string. The following code does what you need:
char* reverse(char* input)
{
int len = strlen(input);
char* temp = new char[len + 1];
for (int i = len; i >= 0; --i)
{
temp[len-i-1] = input[i];
}
temp[len] = '\0';
return temp;
}
You could use a std::stack to reverse your input:
std::stack<char> s;
char c;
while (std::cin >> c)
{
s.push(c);
}
while (!s.empty())
{
std::cout << s.top();
s.pop();
}
It's 2021. Use the STL. If your instructor isn't aware of it or doesn't allow you to use it, your instructor is not keeping up-to-date and you should fire your instructor.
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string input{};
while(std::getline(std::cin, input)) {
std::reverse(std::begin(input), std::end(input));
std::cout << input << '\n';
}
return 0;
}
There's quite many things wrong with the code as many people have already mentioned! Since you want to implement this without using STL it can be done this way,
#include <iostream>
using namespace std;
#include <cstring>
void reverse(char* input,int len) { //added len as argument
char temp[len];
for(int i=len-1; i>=0; --i) {
temp[len-i-1]=input[i];
cout<<temp[len-i-1]; //printing while reversing
}
cout<<endl;
}
int main()
{
char input[100];
int len=0;
//using do while since it has to run atleast once
do{
cin.getline(input,100);
len=strlen(input);
input[len]='\0';
if(len!=0)
reverse(input,len);
}while(len!=0) ;
return 0;
}

How to know the number of digits in an integer

I'm new to programming, and I'm wondering, how can I know the number of digits in an integer that the user enters? For example: the user enters a number like 123456, how can I know that the user enters 6 digits? I don't want to use a for loop to get user input because I don't want the user to enter each digit after a space or enter.
Right now, I'm converting a number to an array of digits so I can have control over them, but the issue is that I don't know how many digits I should loop over, because I don't know how many digits are in the number.
Can I get the user's input as a string and then use string.length and convert it to an array of digits?
#include <iostream>
using namespace std;
int main()
{
int N;
cin >> N;
while(N--)
{
int num;
cin >> num;
int arr[1000];
for (int i=0 ;i<???;i++)
{
arr.[i]=num%10;
num = num /10;
}
}
}
an easier way to do this is to convert it to a string then count the length of said string
#include <iostream>
#include <string>
using namespace std;
int main() {
int n;
cin >> n;
string str = to_string(n);
cout <<"the length of" <<str << "is:" <<str.length() <<"\n";
}
typing in a 41 will print out.
the length of 41 is 2
while (num != 0)
{
arr.[i]=num%10;
num = num /10;
}
is a common pattern that's close to what you already have.
Although you can do what you mentioned in your question and someone suggested in the comments and get the input as a string and use string.length.
Yes, you can read in the user's input as a std::string instead of as an int, and then you can use std::string::size() (or std::string::length()) to get the number of characters in the string, eg:
#include <iostream>
#include <string>
int main()
{
std::string S;
std::cin >> S;
int arr[1000] = {};
for (size_t i = 0; i < S.size(); ++i)
{
arr[i] = (S[i] - '0');
}
return 0;
}
Alternatively:
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
std::string S;
std::cin >> S;
int arr[1000] = {};
std::transform(S.begin(), S.end(), arr, [](char ch){ return int(ch - '0'); });
return 0;
}
Either way, if needed, you can check if the std::string represents a valid integer using std::stoi() or std::strtol() or other similar function, or by putting the std::string into a std::istringstream and then reading an integer from it.
Otherwise, you can read the user's input as an int and then convert it to a std::string for processing:
#include <iostream>
#include <string>
int main()
{
unsigned int N;
std::cin >> N;
std::string S = std::to_string(N);
int arr[1000] = {};
for (size_t i = 0; i < S.size(); ++i)
{
arr[i] = (S[i] - '0');
}
// or:
// std::transform(S.begin(), S.end(), arr, [](char ch){ return int(ch - '0'); });
return 0;
}
Otherwise, if you really want to read in an int and loop through its digits directly, you can use something more like this:
#include <iostream>
int main()
{
unsigned int N;
std::cin >> N;
int arr[1000] = {};
size_t i = 0;
while (N != 0)
{
arr[i++] = num % 10;
num /= 10;
}
return 0;
}

Creating strings by splitting a char array

As part of my homework assignment, I have to split a char[] by its indices. So for example, the main function looks like:
int main()
{
char str[] = "A string to be split into given number of parts";
int split_size;
cout << "Enter the size of the part: ";
cin >> split_size;
int size = sizeof(str) / sizeof(str[0]);
SplitString(str, split_size, size);
int wait;
cin >> wait;
return 0;
}
Then using the function SplitString, the first x elements are printed, new line, then the next.
My first idea, was to use two for loops. One loops through the splits (i.e. if there are 4 splits, the range on this loop is 0 to 3), then the second loops through the split itself, iterating over the array elements.
My SplitString() function looks like this:
void SplitString(char str[], int split_size, int size) {
int parts = size / split_size;
for (int i = 0; i < parts; i++) {
for (int j = 0; j < split_size; j++) {
j = split_size * i;
cout << str[j];
}
cout << endl;
}
}
Is there an easier way to do this? I know in Python, you can use the arr[1:] to grab a range of elements from the array. Is there anything similar in C++? Is there some flaw in my logic? Is there something wrong with my code?
cout comes with a write function that takes a pointer and a size argument.
for (int i = 0; i < parts; i++) {
cout.write (str+i*split_size, split_size)
cout << endl;
}
Note that the code above does not check if the string is actually long enough. If the total size is not equal the split_size times a whole number, you will have to add an additional check.
Also, note that this:
int size = sizeof(str) / sizeof(str[0]);
can be written as:
int size = sizeof(str);
instead because the size of a char is always 1.
You can use std::string for this. Alternatively, if your compiler supports C++17, you can use std::string_view as the first argument of SplitString to avoid unnecessary copying.
#include <algorithm>
#include <iostream>
#include <string>
void SplitString(std::string s, std::size_t split_size)
{
while(!s.empty())
{
auto size = std::min(split_size, s.size());
std::cout << s.substr(0, size) << '\n';
s = s.substr(size, std::string::npos);
}
}
int main()
{
char str[] = "A string to be split into given number of parts";
int split_size = 5;
SplitString(str, split_size);
return 0;
}
Live example.

sorting array of strings one off

This code is supposed to make a array of strings, randomly order them, and then print the order. Unfortunately it adds a blank line in one of the spaces ( i think this is getline's doing). Any ideas how to fix that? I tried setting array [0] = NULL; it complains about operators...
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <string>
#include <cstdlib>
using std::cout;
using std::endl;
using namespace std;
void swap (string &one, string &two)
{
string tmp = one;
one = two;
two = tmp;
}
int rand_loc (int size)
{
return (rand() % size);
}
int main()
{
srand(time(NULL));
int size;
cin >> size;
string *array = new string[size];
//array[0] = NULL ;
for (int x = 0; x < size; x++)
{
getline(cin, array[x]);
}
//for (int x = 0; x < size; x++)
//{
// swap (array[rand_loc(size)], array[rand_loc(size)]);
//}
cout << endl;
for (int x = 0; x < size; x++)
{
//out << array[x] << endl;
int y = x + 1;
cout<<y<<"."<<" "<<array[x]<<endl;
}
delete[] array;
}
The first call to getline() will immediately hit the newline that the user entered after inputting size, and will therefore return an empty string. Try to call cin.ignore(255, '\n'); before the first call to getline(). This will skip up to 255 (an arbitrarily selected number) characters until a \n is encountered (and the newline will be skipped as well).
Edit: As #Johnsyweb and #ildjarn point out, std::numeric_limits<streamsize>::max() is a much better choice than 255.