I need help swapping this string [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
#include <iostream>
using namespace std;
int main()
{
string sentence;
string output;
string product1;
string product2;
char pr1;
string product;
int i;
getline (cin,sentence);
char pr2;
cin >> pr1;
cin >> pr2;
for (i=0; i < sentence.length();i++){
pr1 = sentence[i]; //asdfg---> g
pr2 = sentence[0]; //--> a
}
output += pr1+sentence+pr2;
cout << output;
return 0;
}
This code is made to swap letters, but for example when I enter asdfg I get gaasdfga. When I enter that, I want to swap g and a. Any idea what I should do? Any idea what's wrong, and how I can improve it?

The below assigns new values to pr1 and pr2. The characters you entered will be lost.
pr1 = sentence[i]; //asdfg---> g
pr2 = sentence[0]; //--> a
To swap the first found of each of the two entered characters, use std::string::find and then std::swap
Example:
#include <utility>
#include <string>
#include <iostream>
int main() {
std::string sentence = "asdfg";
char pr1 = 'g';
char pr2 = 'a';
auto pos1 = sentence.find(pr1);
auto pos2 = sentence.find(pr2);
if(pos1 != sentence.npos && pos2 != sentence.npos) {
std::swap(sentence[pos1], sentence[pos2]);
}
std::cout << sentence << '\n';
}
Output:
gsdfa
An alternative to std::swap(sentence[pos1], sentence[pos2]); would be to do the swap manually:
char temp = sentence[pos1];
sentence[pos1] = sentence[pos2];
sentence[pos2] = temp;
or via a user defined swapper function that you call just like you'd call std::swap:
template<class T>
void swapper(T& lhs, T& rhs) {
// move construct a temporary variable from the argument on the
// left hand side
T temp = std::move(lhs);
// move assign the left hand side from the right hand side
lhs = std::move(rhs);
// move assign the right hand side from the temporary variable
rhs = std::move(temp);
}

Related

strcmp can't convert char* to const char* in a prefix evaluation code (c++) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
I'm writing a code to evaluate a prefix expression. The values of the expression are separated by spaces. So if the input is "+ * 87 89 666", I should get 8409 as the answer. The concept of my code is to store the values to an array and then evaluate them value by value. Right now I'm stuck at the switch part because the compiler says invalid conversion from char to const char*
#include <iostream>
#include <bits/stdc++.h>
#include <algorithm>
#include <stack>
#include <string>
#include <sstream>
using namespace std;
char n[99999][6]={};
int evaluatePrefix(int l)
{
stack<int> Stack;
for (int j = l; j >= 0; j--) {
string x=n[j];
if (n[j][0]!='+' || n[j][0]!='-' || n[j][0]!='*' || n[j][0]!='/'){
stringstream ss;
int a;
ss<<x;
ss>>a;
Stack.push(a);
}
else {
int o1 = Stack.top();
Stack.pop();
int o2 = Stack.top();
Stack.pop();
if (strcmp(n[j], '+')==0){
Stack.push(o1 + o2);
}
else if (strcmp(x, '-')==0){
Stack.push(o1 - o2);
}
else if (strcmp(x, '*')==0){
Stack.push(o1 * o2);
}
else if (strcmp(x, '/')==0){
Stack.push(o1 / o2);
}
}
}
return Stack.top();
}
int main()
{
char e[99999], w[99999];
int i=0;
scanf("%[^\n]%*c",e);
char *token = strtok(e, " ");
while (token != NULL)
{
strcpy(n[i], token);
token = strtok(NULL, " ");
}
return 0;
}
You wrote:
if (strcmp(n[j], '+')==0)
n[j] decays into a char*, but '+' is a single char, not a char*. strcmp needs two char pointers.
https://en.cppreference.com/w/c/string/byte/strcmp
So, you should use:
if (strcmp(n[j], "+")==0)

Recursion to count words and redundant words in a sentence in c++ [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
Hi i'm trying to count the words in a sentence that is input by the user and this is the code i've written
void Count_Words( )
{
int count=0;
for (i = 0; inserted_text[i] != '\0';i++)
{
if (inserted_text[i] == ' ')
count++;
}
cout << "Word Count: " << count + 1;
}
I need to write this using recursion but i can't figure out how.
Also i need to count the redundant words in the sentence using recursion how do i do that?
I can't use mapping i need to use basic logic to do this. Is there anyway i can do this only with basic logic?
I agree with Hatted Rooster (this is not a good fit for recursion). I guess it serves a teaching purpose. So here is another option.
countWords() returns the number of words for the given substring until its end. To calculate the words for substring 0..n, we can calculate the words for substring 1..n first. And if character 0 is a space, add 1 to that.
int countWords(const char* str)
{
if(*str == '\0')
return 1; // last word
return countWords(str + 1) // how many words are in the remaining substring?
+ (*str == ' ' ? 1 : 0); // count if the beginning of the current substring is a space
}
int main()
{
std::string input = "test test test";
std::cout << countWords(input.c_str()); // 3
}
It doesn't really make sense to use recursion here but anyway, this would be one way to do it:
void Count_Words(int& i, const std::string& inserted_text, int& count)
{
if (inserted_text[i] == '\0')
{
++count; // last word
return;
}
if (inserted_text[i] == ' ')
++count;
Count_Words(++i, inserted_text, count); //recurse
}
int main()
{
std::string input = "test test test";
int i = 0;
int count = 0;
Count_Words(i, input, count);
std::cout << count; // 3
}
The thing to take away from this code is that references are a powerful tool to achieve correct recursion as seen in the function parameters.
As the other answer stated, this is really not a problem that should be resolved using recursion. What if there are thousands of words? That would exhaust the stack memory at some point.
In any event, here is one way to do this recursively:
#include <sstream>
#include <string>
#include <iostream>
void Count_Words(std::istringstream& strm, int& count)
{
std::string word;
if ( strm >> word ) // if there is a word, then increment the count
{
++count;
Count_Words(strm, count); // go to next word recursively
}
}
int Count_Words(std::string inserted_text)
{
// This is the setup for the recursive calls
std::istringstream strm(inserted_text);
int count = 0;
// start the recursion
Count_Words(strm, count);
return count;
}
int main()
{
std::string test = "This has four words";
std::cout << Count_Words(test);
}
Output:
4

How can I erase my string way quicker [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
I am supposed to write a program that takes in string like "pre#ogrann##mmink#g" and returns "programming", it is like your backspace button is broken and when you hit it you get '#' instead of erasing the char out, and I have to fix it. I have working code here under but it is way to slow, and I might have to deal with huge string, any suggestion how I could do it better/faster?
#include <string>
#include <iostream>
using namespace std;
int main() {
string str;
while(cin >> str) {
bool done = false;
while(!done) {
if((int)str.find('#')>-1) {
str.erase(str.find('#')-1, 2);
} else {
done = true;
}
}
cout << str << endl;
}
}
Here's how I would do it. I haven't tested it to see if it is actually faster, but as it has a complexity of O(N), I think it should be fast enough:
while (std::cin >> input) {
std::string result;
result.reserve(input.length());
for (auto ch : input) {
if (ch == '#') {
if (result.length() > 0)
result.pop_back();
continue;
}
result += ch;
}
std::cout << result << '\n';
}
#include <iostream>
#include <string>
using namespace std;
string s = "pre#ogrann##mmink#g";
int main() {
string out;
int len = s.length();
for (int i = 0; i < len; i++) {
if(s[i] == '#') {
s.erase(i-1,2);
len = s.length();
i -= 2;
}
}
cout << s;
return 0;
}
This produces a working output.

C++ char array to int [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am new to C++ and I am creating a small program. Part of it I have created a way of converting a char array to set of int's. But i was just wondering if there is a better way (more efficient and/or uses better C++ standards). Like for example using atoi on spliced part of the array for each number for etc.
So I start of reading a set of numbers e.g. "11 2 123 44" from a file into a char * array and now want to convert them into there respective values currently doing it as follows:
//char * char_cipher; //{'1', '1', ' ', '2', ... , '4'}
//int length; //length of char_cipher
string s = "";
vector<int> cipher_int;
for (int i = 0; i <= length; i++) {
if (char_cipher[i] == ' ') {
//create num
cipher_int.push_back(stoi(s));
s = ""; //empty num
}
else {
//add to string
s += char_cipher[i];
}
}
Any help would be much appreciated thanks :)
Your code is pretty close. The problem is that you never push the last number in char_cipher onto cipher_int, because there's no space after it. You need to do an extra check after the loop is done.
for (int i = 0; i <= length; i++) {
if (char_cipher[i] == ' ') {
//create num
cipher_int.push_back(stoi(s));
s = ""; //empty num
}
else {
//add to string
s += char_cipher[i];
}
}
if (s != "") {
cipher_int.push(back(stoi(s));
}
Let the STL do the parsing for you. You can use a std::istringstream for that, eg:
#include <string>
#include <sstream>
#include <vector>
std::string str_cipher; //"11 2 123 44"
std::vector<int> cipher_int;
std::istringstream iss(str_cipher);
int num;
while (iss >> num) {
cipher_int.push_back(num);
}
Alternatively:
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <iterator>
std::string str_cipher; //"11 2 123 44"
std::vector<int> cipher_int;
std::istringstream iss(str_cipher);
std::copy(
std::istream_iterator<int>(iss),
std::istream_iterator<int>(),
std::back_inserter(cipher_int)
);

Concatenation of strings [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
In vector c++, I have strings, for example :
ACTT CTTG TTGA TG TGA GAG, as you can see, they superpose
ACTT
CTTG
TTGA
TG
GAG
So in the alignment we can see
ACTTGAG
I want to concatenate them as you can see above and put to another vector. I've tried use substring function, but it doesn't work...
Here's a fairly simple algorithm to overlap two strings:
#include <string>
std::string overlap(std::string first, std::string const & second)
{
std::size_t pos = 0;
for (std::size_t i = 1; i < first.size(); ++i)
{
if (first.compare(first.size() - i, i, second, 0, i) == 0)
{
pos = i;
}
}
first.append(second, pos, second.npos);
return first;
}
Usage:
std::string result = overlap("abcde", "defgh");
And to overlap a whole range, use std::accumulate:
#include <algorithm>
#include <iostream>
#include <vector>
int main()
{
std::vector<std::string> strings = {"abc", "def", "fegh", "ghq"};
std::cout << std::accumulate(strings.begin(), strings.end(), std::string(), overlap) << std::endl;
}
Assuming you still use the same code as the last question you might want to consider using the first index you have in your element (it[0]). You could add this result to a string and print it.
Use:
std::string space = "";
std::string result = "";
auto end = vec.rend();
for(auto it = vec.rbegin(); it != vec.rend(); ++it ) {
if (it == end - 1) {
result += *it;
}
else {
result += it[0];
}
std::cout << space << *it << std::endl;
space += " ";
}
std::cout << result << std::endl;