How can I erase my string way quicker [closed] - c++

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.

Related

I am trying to encode a string by breaking it down to characters c++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am trying to change "Hello this is The friend" to "Hello 1Yhis is 1Yhe friend"
#include <iostream>
using namespace std;
int main()
{
string str("Hello this is The friend");
for ( int i = 0 ; i < str.size(); i++)
{
if (str[i] == 'T')
{
str[i] = '1Y';
}else if (str[i] == 't')
{
str[i] = '1Y';
}
}
cout<<str;
}
The output is "Hello Yhis is Yhe friend".
The implementation of std::string is std::basic_string<char>, which means you can only use single-characters in it.
You are making use of an illegal multi-character constant '1Y'. I guess your compiler warned you about that. Because he cannot insert a multi-character, the compiler chose one for you, i.e. 'Y' in your case.
If you want to replace chars with something else than another single-character, you should take a look at solutions such as How to replace all occurrences of a character in string?
You can't replace a single-byte char with a multi-byte character using operator[]. You need to do something more like this instead:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str("Hello this is The friend");
string::size_type i = 0;
while (i < str.size())
{
if ((str[i] == 'T') || (str[i] == 't'))
{
str[i] = '1';
str.insert(i+1, 'Y');
// or:
// str.replace(i, 1, "1Y");
i += 2;
}
else
++i;
}
cout << str;
}
Alternatively:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str("Hello this is The friend");
string::size_type i = 0;
while ((i = str.find_first_of("Tt", i)) != string::npos)
{
str[i] = '1';
str.insert(i+1, 'Y');
// or:
// str.replace(i, 1, "1Y");
i += 2;
}
cout << str;
}
Alternatively:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string str("Hello this is The friend");
ostringstream oss;
for (string::size_type i = 0; i < s.size(); ++i)
{
if ((s[i] == 'T') || (s[i] == 't'))
oss << "1Y";
else
oss << s[i];
}
cout << oss.rdbuf();
}

To check if a string has all Unique Characters in C++ [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Am trying to find If a string has all Unique characters and below is my code, But I get the error "invalid types 'char[int]' for array subscript" in the if statement of the function Unique char, can anyone tell me how to correct this
#include <iostream>
#include<cstring>
using namespace std;
bool unique_char(char);
int main()
{
char s;
bool check;
cout << "Enter any string" << endl;
cin>>s;
check = unique_char(s);
if(check)
cout<<"there are no duplicates";
else
cout<<"the string has duplicates";
return 0;
}
// The if statement in this section has the error
bool unique_char(char s)
{
bool check[256] = {false};
int i=0;
while (s != '\0')
{
if (check **[(int) s[i]]**)
return false;
else
{
check[(int) s[i]] = true;
i++;
}
}
}
You need to pass char array rather than a single char.
int main()
{
char s[1000]; // max input size or switch to std::string
bool check;
cout << "Enter any string" << endl;
cin>>s;
check = unique_char(s);
if(check)
cout<<"there are no duplicates";
else
cout<<"the string has duplicates";
return 0;
}
bool unique_char(char* s)
{
bool check[256] = {false};
int i=0;
while (s[i] != '\0')
{
if (check[(int) s[i]])
return false;
else
{
check[(int) s[i]] = true;
i++;
}
}
return true;
}

I am getting a segmentation fault in this code and can't understand why?

I am trying to code a program where it takes a program as an input and prints out all the comments written in that program in a separate line.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string str;
while(getline(cin,str)) {
int i;
// cout<<str;
for(i=0;str[i]!='/' && str[i+1] !='/';i++);
//cout<<i;
for(i;str[i]!='\n';i++) {
// cout<<i;
cout<<str[i];
}
cout<<endl;
}
return 0;
}
I am getting a segmentation fault in this code and I can't understand why. This is part of a code of a problem in hackerrank https://www.hackerrank.com/challenges/ide-identifying-comments/copy-from/12957153
As commented in your question your code is wrong. First you are treating std::string object, returned by getline, as character array. Secondly your for loops never end if there is no // or \n found in input string. So obviously it will crash. Below is the modified code.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string str;
while(getline(cin,str)) {
int i;
// cout<<str;
size_t len = str.length();
const char *cstr = str.c_str();
for(i=0; (cstr[i]!='/' && cstr[i+1] !='/' && i < len); i++)
//cout<<i;
for(; cstr[i]!='\n' && i < len;i++) {
// cout<<i;
cout<<cstr[i];
}
cout<<endl;
}
return 0;
}
int main() {
while(getline(cin,str)) {
int i, len = str.size();
//always make sure that you are not accessing
//contents after your string has ended
for(i=0; i < (len - 1) && !(str[i] == '/' && str[i+1] == '/'); i++);
//note that i here might be the last alphabet
//if there's no comment
if(i < len && str[i] != '/')
i++;
//checking if str[i] != '\n' is not a good idea
//as c++ stl strings are not temrinated by '\n'
if(i < len) {
for(; i < len; i++)
cout << str[i];
cout << endl;
}
}
return 0;
}
Also note that both of the following codes won't terminate at the 4th character, c++ stl strings are not terminated by these characters.
string str = "hahahaha";
str[4] = '\n';
cout << str;
str[4] = '\0';
cout << str;
This is much easier to write and probably much faster than the other solutions to date.
#include <iostream>
int main()
{
std::string str;
while (std::getline(std::cin, str))
{
size_t loc = str.find("//");
if (loc != str.npos)
{
std::cout << str.substr(loc + 2)<< std::endl;
}
}
return 0;
}
It is also wrong.
Here is a nice, clean, and simple state machine version. Also pretty close to worst-case for speed. Thing is it's closest to being right, even though it is also wrong.
#include <iostream>
enum states
{
seeking1,
seeking2,
comment
};
int main()
{
std::string str;
while (std::getline(std::cin, str))
{
states state = seeking1;
for (char ch:str)
{
switch (state)
{
case seeking1:
if (ch == '/')
{
state = seeking2;
}
break;
case seeking2:
if (ch == '/')
{
state = comment;
}
else
{
state = seeking1;
}
break;
case comment:
std::cout << ch;
break;
}
}
if (state == comment)
{
std::cout << std::endl;
}
}
return 0;
}
Why are these approaches all wrong? Consider the line
cout << "Hi there! I am \\Not A Comment!" << endl;`
You can't just look at the \\, you also need the context. This is why the state machine above is the better option. It can be modified to handle, at the very least, states for handling strings and block comments.

Why Does My Program Keep Crashing (C++)? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I don't understand why this won't run properly in Visual Studio 2012
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
char nullChar()
{
char ch;
int ran = (rand() % 52);
if (ran < 26)
{
ch = (char) ('a'+ ran);
}
else
{
ch = (char) ('A'+ ran - 26);
}
return ch;
}
int main(int argc, char *argv[])
{
cout << "Enter a string";
int nullNum = 0;
nullNum = atoi(argv[2]);
if (strcmp(argv[1], "-d") == 0)
{
int count = -1;
do
{
int c = cin.get();
count++;
if(count == nullNum)
{
cout.put(c);
count = -1;
}
} while (!cin.eof()) ;
}
if(strcmp(argv[1], "-e") == 0)
{
char c = cin.get();
while(!cin.eof())
{
for (int i = -1; i < (nullNum-1); ++i)
{
cout << nullChar();
}
cout << c;
c = cin.get();
}
}
}
The code compiles perfectly. I'm suspecting something in a loop but I can't figure it out. I also think it ran perfectly a few days ago but now it's not. Is that possible?
Im not sure if you passed a parameter. But aside from that you should always check argc before using argv[xyz]. My guess is you get a segfault, because there is no argv[1] and argv[2]

I want an array of cstrings separated by white space

I am trying to get user input and put it into an array of cstrings separated by a space. When I print the array to the screen though I get nothing. I am sure I am doing something stupid, but I have been stuck trying different ways for a while. Any help would be appreciated. Here is the code.
#include <iostream>
#include <cstring>
using namespace std;
void stuff(char command[][25], int length)
{
char ch;
for(int i = 0; i < length; i ++)
{
int b = 0;
cin.get(ch);
while(!isspace(ch))
{
command[i][b++] = ch;
cin.get(ch);
}
command[i][b] = '\0';
cout << endl;
}
}
int main()
{
char cha[10][25];
char ch;
int len = 0;
while(ch != '\n')
{
cin.get(ch);
if(isspace(ch))
{
len++;
}
}
stuff(cha,len);
for(int i = 0; i < len; i++)
{
cout << cha[i] << endl;
}
cout << len << endl;
return 0;
}
a) ch is undefined when you first test it with while (ch != '\n'). Initialize it to zero or something.
b) You don't write any values into cha in the while loop. Perhaps something like:
int pos = 0;
while(ch != '\n') {
cin.get(ch);
if (isspace((unsigned)ch)) {
if (pos > 0) {
++len;
pos = 0;
}
}
else {
cha[len][pos] = ch;
++pos;
}
}
c) You are reading the stream again in stuff(...) but have already consumed what you wanted to get from the stream in main().
d) This code suffers from a number of buffer overrun and stack corruption opportunities. perhaps use a std::vector<std::string> instead. If it runs out of memory it will throw an exception rather than make a mess on the stack.
Perhaps something like this (untested):
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void main()
{
typedef std::vector<std::string> strvec;
strvec cha;
std::string s;
char ch = 0;
while(ch != '\n') {
cin.get(ch);
if (isspace((unsigned)ch)) {
if (!s.empty()) {
cha.push_back(s);
s.clear();
}
}
else {
s.push_back(ch);
}
}
// don't need to call 'stuff' to null terminate.
for (strvec::iterator i = cha.begin(); i != cha.end(); ++i) {
cout << *i << endl;
}
cout << cha.size() << endl;
}
This could be a little more efficient than it is but hopefully it is easy to understand.
You are reading the whole input in the while cycle in the main to read length(number of strings), but you never store it. Later on in stuff cin.get will read nothing. Maybe store the input in cha during the first cycle?