This is a function I am writing that switches the characters of a string, but I am getting "replace was not declared in this scope".
#include <string>
using namespace std;
string rs(string j)
{
srand(time(NULL));
int len = j.size();
int ran1 = rand() % len;
srand(time(NULL) + 1);
int ran2 = rand() % len;
replace(j, ran1, ran2);
cout << j << endl;
return j;
}
Obviously I have something wrong with the function. Any help is appreciated.
replace() is a member function of the string class which is most probably why you're getting the error.
But also, replace() doesn't switch the substrings, it just replaces one with the other.
If you want to switch two substrings of a string using the replace function, you can try doing it by replacing the line:
replace(j, ran1, ran2);
with
string substr_at_ran1 = j.substr(ran1, 1);
j.replace(ran1, 1, j.substr(ran2, 1));
j.replace(ran2, 1, substr_at_ran1);
This is switching the substring of j starting at position ran1 and length 1 with a substring of j at position ran2 and length 1.
Not enough information was provided to properly answer the question, but I'll take a stab at it.
The replace() function I'm assuming is a function that probably doesn't exist in your program, since you didn't provide it.
Assuming that you want your function rs() to randomly swap two characters, here is a program that does just that.
#include <string>
#include <iostream>
using namespace std;
string rs(string j)
{
auto len = j.size();
if (len == 0) //added because your code didn't account for empty strings
{
return j;
}
auto ran1 = rand() % len;
auto ran2 = rand() % len;
swap(j[ran1], j[ran2]);
cout << j << endl;
return j;
}
int main()
{
srand(time(NULL)); //do not use srand in modern C++!
rs("stack overflow");
}
I would also advise against making function names like rs, since its functionality cannot be gleaned from the name alone. swap_random_characters would be a better name.
Related
I am writing a code in C++ to reverse all the words in a string without changing the order of the list
This is my code:
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s = "God Ding";
int n = s.size();
int i = 0, j = 0;
while(j < n){
if(s[j] == ' ' || j == n-1){
reverse(s.begin()+i, s.begin()+j);
j++;
i = j;
}
else{
j++;
}
}
cout << s;
return 0;
}
Expected Output: "doG gniD"
My output: doG Ding
2nd input: "Let's take LeetCode contest"
Expected Output: "s'teL ekat edoCteeL tsetnoc"
My Output: "s'teL ekat edoCteeL contest"
Everything is working fine but only the last word is not getting reversed
You need either to detect in your if the special situation of processing the last character, or add an extra reverse after the while, if the last word was not processed (i.e. the last char was not a space).
In your case, you've added the detection of last character, but did not process the reverse before the increment, as would be the case if the word ended with a space. To correct this situation, you must take into account this special situation:
if(s[j] == ' ' || j == n-1){
reverse(s.begin()+i, s.begin()+j+(j==n-1?1:0));
// ^ (if it's last, take +1)
...
I think this would be a better implementation for your code:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string s = "God Ding", reversed_string;
std::string word;
std::istringstream ss(s); // Declaring an in string stream
while (std::getline(ss, word, ' ')) // Here getline gets every word in ss and stores it in the variable 'word'
{
// This loop reverses the variable 'word'
for (int i = word.size() - 1; i >= 0; i--)
{
reversed_string.push_back(word[i]);
}
reversed_string.push_back(' ');
}
std::cout << reversed_string;
return 0;
}
Also look up to why is "using namespace std" considered as a bad practice.
Here you have a working example:
#include <string>
#include <algorithm>
#include <iostream>
int main()
{
std::string s = "God Ding";
int i = 0;
int j = 0;
while (i <= s.length()) {
if (i == s.length() || s[i] == ' ') {
std::reverse(s.begin() + j, s.begin() + i);
j = i + 1;
}
i++;
}
std::cout << s << std::endl;
return 0;
}
I changed a lot of things.
These are the issues you need to fix:
Make your loop go beyond the last char.
Reverse if j (from your code) is beyond the last char.
In order to reverse a word, you need i to index the first char, and j to index the char after the last one.
However, your loop exits whenever j indexes the char after the last one. That's why it never reverses the last word.
The simplest fix is to do one more check after the loop exits, and reverse the last word if there is one:
while(j < n) {
if(s[j] == ' ') { // remove the `j==n-1` test
reverse(s.begin()+i, s.begin()+j);
j++;
i = j;
} else {
j++;
}
}
if(i < j) {
reverse(s.begin()+i, s.begin()+j);
}
The alternative would be to rewrite the loop in some way that finesses the problem. I don't really recommend this, given that you have something that almost works and that you know how to fix.
The purpose of this code is to insert an x in between repeating letters. For example, if I were to input "CoolBoolFallmoose", the output would be "CoxolBoxolFalxlmoxose".
The code is also supposed to make an even number of pairs of letters, so if there is an odd amount of characters, an x is added to the end of the string. An example for this would be if we had "ball", it would become "balxlx" to make even pairs: "ba" "lx" "lx".
This is the code I have so far:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main(){
string cipher, plain, paired = "";
cout << "input plaintext(no spaces, lowercase):\n";
cin >> plain;
for (int i=0;i<plain.length();i++){
if (plain[i]==plain[i+1]){
plain.insert(i,'x');
}
paired[i]=paired[i];
cout<<paired[i];
}
if (paired.length() % 2!= 0){
paired=+'x';
}
cout<<paired<<endl;
return 0;
}
The output I get is just the same as my input, no "x" added in any place.
The issue I am having is, every time I try to use the append() or insert() function for strings, I get an error from my compiler, which is xCode. Is there another way to solve this code?
EDIT: The error says:
No matching member function to call for insert
It also comes up for append().
I don't really know what you wanted to do with this part:
paired[i]=paired[i];
cout<<paired[i];
but otherwise the logic is good. Here is my take on it, x is a counter:
#include <iostream>
#include <string>
using namespace std;
int main(){
string m,n;
int x = 0;
cout << "Input: " << endl;
getline(cin, m);
for(int i = 0;i < m.length();i++){
x++;
n = n + m[i];
if(m[i] == m[i+1]){
n = n + 'x';
x++;
}
}
if((x % 2) != 0){
n = n + 'x';
}
cout << n;
return 0;
}
If you look at the available overloads of std::string::insert(), you will see that your statement plain.insert(i,'x'); does not match any of them, hence the compiler error. The overloads that takes a single char require either:
an index and a count (you are omitting the count)
an iterator and an optional count
There is, however, a couple of overloads that take just an index and a value, but they require a const char* or a std::string, not a single char.
Also, paired[i]=paired[i]; is a no-op. Except in your case, since paired has a size() of 0 since you never append anything to paired, so actually any access to paired[...] is undefined behavior.
Try this instead:
#include <iostream>
#include <string>
using namespace std;
int main(){
string plain, paired;
cout << "input plaintext(no spaces, lowercase):\n";
cin >> plain;
paired = plain;
for (string::size_type i = 1; i < paired.size(); ++i){
if (paired[i] == paired[i-1]){
paired.insert(i, 1, 'x');
// or: paired.insert(paired.begin()+i, 'x');
// or: paired.insert(i, "x");
// or: paired.insert(i, string{'x'});
// or: paired.insert(paired.begin()+i, {'x'});
++i; // skip the x just inserted
}
}
if (paired.size() % 2 != 0){
paired += 'x';
}
cout << paired << endl;
return 0;
}
Demo
A couple of points
First, Although the string.insert function says it takes an int as its first argument it really wants an iterator in this case.
Second, you are inserting elements into your "plain" string which increases its length and you have plain.length within your loop so you create an infinite loop.
Third, insert inserts BEFORE the index so you need to add 1 to I.
The code below will work for your loop:
Int len = plain.length();
Int count = 0;
for (int i = 0; i < len + count; i++)
{
If (plain[i] == plain[i + 1])
{
plain.insert(plain.begin() + (i +1), 'X');
++count;
}
}
cout << plain;
And as, mentioned below, if you want to handle spaces you can use getline(cin, plain) instead of cin.
My logic is as follows :
#include<bits/stdc++.h>
using namespace std;
int main(){
char a[50] = {'h','i',' ','m','e',' ','t','e'};
// k = 4 because i have 2 spaces and for each
// space i have to insert 2 spaces . so total 4
//spaces
int k=4;
for(int i=strlen(a)-1 ; i>0 && k >0 ; i--){
if(a[i] != ' ')
{
a[i+k] = a[i];
a[i] = ' ';
}
else
{
k = k - 2;
}
}
printf("%s" , a);
return 0;
}
I have to character array to solve it. I am able to
do it using string stl
The output i get is
hi---me.
But the answer is
hi---me---te.
Your code is tagged C++. But there is nothing C++ in your code. It is pure C.
And, your are including #include<bits/stdc++.h> and using the std namespace using namespace std;. From now on: Please never ever in your whole life do such things again. Or, stop working with C++.
Additionally never ever use plain C-style array like your char a[50] in C++.
In your code you have some bugs. Most critical is the missing terminating 0 and then calling strlen. Before you use a function, always check somewhere, how this function works. Use meaningful variable names. Write comments. Always check boundaries.
I updated your C-Code:
#include <stdio.h>
int main()
{
// Character String to work on
char charString[50] = "hi me te";
// Check all possible positions in string
for (int index = 0; (index < 49) && (0 != charString[index]); ++index)
{
// If there is a space in the string
if (' ' == charString[index])
{
// Shift all characters one position to the right
for (int shiftPosition = 48; shiftPosition >= index; --shiftPosition)
{
charString[shiftPosition + 1] = charString[shiftPosition];
}
++index;
}
}
// Show result
printf("%s\n", charString);
return 0;
}
And here the C++ solution
#include <iostream>
#include <string>
#include <regex>
int main()
{
// Text to work on
std::string text("hi me te");
// Replace every space with 2 spaces. Print result
std::cout << std::regex_replace(text, std::regex(" "), " ");
return 0;
}
I am working on a problem to print all the non-increasing subsequences with sum equal to a given number n, using recursion. I know there is something wrong with my recursive algorithm, but I have walked through the process multiple times and I cannot find my error. With input 4, my code gives output:
4
431
4322
432211
43213
4321321
43213212
4321321211
I believe the recursion is holding on to previous numbers or sums used in past recursive calls, but cannot find why. Can anybody please help me figure out why the program is not giving correct output?
#include <iostream>
#include <string>
using namespace std;
int n;
void sums(int sum, string str)
{
if (sum==n)
{
cout << str << "\n";
return;
}
for (int i = n-sum; i >= 1; i--)
{
str+=to_string(i);
sums(sum+i, str);
}
}
int main()
{
cin >> n;
string s = "";
sums(0, s);
}
The problem is in your: str+=to_string(i); inside your for loop.
on the first call you have sum 0, str = "", and in the for loop it goes from i = 4, i--. but inside the body you append to str += 4 and call sums(4, "4"), and the error happens on the next loop i--, str += "3" and becomes "43" and sums(3, "43");
You can fix it by not modifying str, but calling
sums(sum + i, str + to_string(i));
From my understanding of recursive functions, I believe there should not be a loop at all! so, replace :
for (int i = n-sum; i >= 1; i--)
{
str+=to_string(i);
sums(sum+i, str);
}
by:
str+=to_string(n-sum);
sums(n-sum, str);
i have a string array that contains 20 words. I made a function that take 1 random word from the array. But i want to know how can i return that word from array. Right now i am using void function, i had used char type but it wont work. Little help here ? Need to make word guessing game.
CODE:
#include <iostream>
#include <time.h>
#include <cstdlib>
#include <stdlib.h>
#include <algorithm>///lai izmantotu random shuffle funckiju
#include <string>
using namespace std;
void random(string names[]);
int main() {
char a;
string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba",
"kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi",
"saule", "parks", "svece", "diegs", "migla", "virve"};
random(names);
cout<<"VARDU MINESANAS SPELE"<<endl;
cin>>a;
return 0;
}
void random(string names[]){
int randNum;
for (int i = 0; i < 20; i++) { /// makes this program iterate 20 times; giving you 20 random names.
srand( time(NULL) ); /// seed for the random number generator.
randNum = rand() % 20 + 1; /// gets a random number between 1, and 20.
names[i] = names[randNum];
}
//for (int i = 0; i < 1; i++) {
//cout << names[i] << endl; /// outputs one name.
//}
}
Make random return string. You also only need to seed the number generator once. Since you only want to get 1 random word from the array, you don't need a for loop.
string random(string names[]){
int randNum = 0;
randNum = rand() % 20 + 1;
return names[randNum];
}
Then, in the main function, assign a string variable to the return value of the random function.
int main() {
srand( time(NULL) ); // seed number generator once
char a;
string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba",
"kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi",
"saule", "parks", "svece", "diegs", "migla", "virve"};
string randomWord = random(names);
cout<<"VARDU MINESANAS SPELE"<<endl;
cin>>a;
return 0;
}
In your question as well as in the previous answer, you are running out of bounds accessing the names array:
int randNum = rand() % 20 + 1;
return names[randNum];
You are never accessing names[0] but instead reach behind the array when addressing names[20].
Additionally srand(time(NULL)) should be called only one time, on the beginning of main() function.
I'm not super familiar with strings, but you should be able to just declare random() as a string function.
Ex:
string random (string names[]);