Reverse a string. Not sure why this logic is wrong. C++ - c++

I am a beginner in solving algorithmic questions. Until now, I have only self-taught coding. So, I am not sure about the proper conventions.
I was trying to solve a question to reverse a string.There is some problem with the code but I am not sure what it is after debugging step-by-step.
class Solution {
public:
string reverseString(string s) {
int n = s.length();
string reverse;
for (int i=0;i<s.length();i++)
{
reverse[i] = s[n-1];
n=n-1;
}
return reverse;
}
};
Input: "Hello"
Output needed: "olleh"
My output: "olleh " (extra space)
Input: A man, a plan, a canal: Panama
Output: No output
I searched online for solutions. There were related to pointers. It would be great if someone helped me understand why this logic doesn't work and why using pointers is a better idea.
ALREADY GIVEN. CANNOT CHANGE:
string stringToString(string input) {
assert(input.length() >= 2);
string result;
for (int i = 1; i < input.length() -1; i++) {
char currentChar = input[i];
if (input[i] == '\\') {
char nextChar = input[i+1];
switch (nextChar) {
case '\"': result.push_back('\"'); break;
case '/' : result.push_back('/'); break;
case '\\': result.push_back('\\'); break;
case 'b' : result.push_back('\b'); break;
case 'f' : result.push_back('\f'); break;
case 'r' : result.push_back('\r'); break;
case 'n' : result.push_back('\n'); break;
case 't' : result.push_back('\t'); break;
default: break;
}
i++;
} else {
result.push_back(currentChar);
}
}
return result;
}
int main() {
string line;
while (getline(cin, line)) {
string s = stringToString(line);
string ret = Solution().reverseString(s);
string out = (ret);
cout << out << endl;
}
return 0;
}

As you create reverse, you have to pass the length of the string as an argument, else the created string will be of size 0. This could look like this:
string reverseString(string s) {
int n = s.length();
string reverse(n,'0');
for (int i=0;i<s.length();i++)
{
reverse[i] = s[n-1];
n=n-1;
}
return reverse;
}

Reversing a string is trivial. Just construct a new one from the reverse iterators:
std::string reverse_str(s.rbegin(), s.rend());
or
std::string reverse_str(s.crbegin(), s.crend());
Here's how I would write your function:
string reverseString(const string& s) {
return {s.crbegin(), s.crend()};
}

Try this out
class Solution {
public:
string reverseString(string s) {
//cout<<"inside func";
int n = s.length();
cout<<n<<endl;
char reverse[sizeof(char)*n];// reverse stores the reverse of original string s
int i= 0;
for ( i=0;i<s.length();i++)
{
reverse[i] = s[n-i-1];
}
return reverse;
}
}
int main()
{
string s,r;
Solution sol;
s= "hello";
r= sol.reverseString(s);
cout<<r<<endl;
cout<<r.length()<<endl;
return 0;
}
when i= 0, n-i-1= n-1 which is the last element of the original string s. So the first element of the reverse string is the last element of s. Next i becomes i+1 i.e 1. This time second element of the reverse string is the last but one element in string s. This procedure is repeated till i < s.length(). The element to get copied is for index i= n-1 and n becomes n-(n-1)-1= 0, so the last element of reverse string is the first element of s. After this the loop exists. No additional extra characters are added.

Related

Palindrome but with a scentence

So writing a palindrome with pointers and boolean. I have it working with a single word but then I began building it to work with a sentence. The problem is I am unsure how to keep the new modified sentence after making it lowercase and getting rid of the spaces for it to return whether it is or isn't a palindrome. It keeps returning the palindrome as false and when I went to check why I see that the program ignores the modification and kept the original string. I can't use "&" on the parameter as I tested it out. Any hints or takes on what I can do to keep the new modified string?
int main()
{
userInput();
return 0;
}
void userInput()
{
char str[90];
std::cout<<"Please enter a string to check if it is a palindrome: ";
std::cin.getline(str, 90);
modifyString(str);
}
void modifyString(char *string)
{
int count = 0;
for (int i=0; i<strlen(string); i++)
{
putchar(tolower(string[i]));
}
for (int i = 0; string[i]; i++)
{
if (string[i] != ' ')
{
string[count++] = string[i];
}
}
string[count] = '\0';
std::cout<<string<<std::endl;
results(string);
}
bool checkPalindrome(char *string)
{
char *begin;
char *end;
begin = string;
end = (string + strlen(string)-1);
while(begin != end)
{
if ((*begin) == (*end))
{
begin ++;
end--;
}
else
{
return false;
}
}
return true;
}
void results(char *string)
{
bool isItPalindrome;
isItPalindrome = checkPalindrome(string);
if( isItPalindrome == true)
{
std::cout<<"\nCongrats, the string is a palindrome!";
}
else
{
std::cout<<"\nThis string is not a palindrome.";
}
}
For starters this definition of main
int main()
{
userInput();
return 0;
}
does not make a sense. According to the function name main the function should perform the main task that is to output whether the entered sentence is a palindrome or not.
This for loop
for (int i=0; i<strlen(string); i++)
{
putchar(tolower(string[i]));
}
does nothing useful. It just outputs the string in the lower case.
This statement
end = (string + strlen(string)-1);
can invoke undefined behavior if an empty string was passed.
This while loop
while(begin != end)
{
if ((*begin) == (*end))
{
begin ++;
end--;
}
else
{
return false;
}
}
also can invoke undefined behavior for a string containing an even number ofo characters because after this if statement
if ((*begin) == (*end))
{
begin ++;
end--;
}
if the two adjacent characters are equal then begin after incrementing will be greater than end after its decrementing. And as a result the loop will continue its iteration.
In general the approach when the original string is changed is just a bad approach.
Your program has too many functions. It is enough to write one function that will determine whether the passed string is a palindrome or not.
Here is a demonstrative program.
#include <iostream>
#include <cstring>
#include <cctype>
bool checkPalindrome( const char *s )
{
const char *t = s + std::strlen( s );
do
{
while ( s != t && std::isspace( ( unsigned char )*s ) ) ++ s;
while ( s != t && std::isspace( ( unsigned char )*--t ) );
} while ( s != t &&
std::tolower( ( unsigned char )*s ) == tolower( ( unsigned char ) *t ) &&
++s != t );
return s == t;
}
int main()
{
const size_t N = 100;
char s[N] = "";
std::cout << "Please enter a string to check if it is a palindrome: ";
std::cin.getline( s, N );
std::cout << '\n';
if ( checkPalindrome( s ) )
{
std::cout << "Congrats, the string is a palindrome!\n";
}
else
{
std::cout << "This string is not a palindrome.\n";
}
return 0;
}
Its output might look like
Please enter a string to check if it is a palindrome: 1 23 456 6 54 321
Congrats, the string is a palindrome!
Okay, I solved it!
As one of the users on here brought up a point that my lowercase did not modify the string and only prints it out. I try my best to solve the problem and I think I found the solution and everything works perfectly fine. comment back to debug it if you like to see how it looks but what I did was create a for loop again for the lower case but made another pointer with it. here how it looks.
for (char *pt = string; *pt != '\0'; ++pt)
{
*pt = std::tolower(*pt);
++pt;
}
Now that definitely changes the string into a lower case and keeps it as a lower case.
so now the modified function looks like this and ready to take any sentence palindrome you give it. Example: A nUt fOr a jAr of tUNa. We make this all lowercase and take out space and boom palindrome and return true.
void modifyString(char *string)
{
int count = 0;
for (char *pt = string; *pt != '\0'; ++pt)
{
*pt = std::tolower(*pt);
++pt;
}
for (int i = 0; string[i]; i++)
{
if (string[i] != ' ')
{
string[count++] = string[i];
}
}
string[count] = '\0';
//take out the forward slash below to see how it looks after being modified
// std::cout<<std::endl<<string<<std::endl;
results(string);
}

Why am I getting string reversal wrong with a trailing space character?

I am unable to get why there is a space and it is getting me wrong.
Below is the code I wrote for the solution
Why there is blank space char at the end of the string at the end even after reversing my string.
Question
class Solution {
public:
string minRemoveToMakeValid(string s) {
string str = "";
int n = s.length();
int open=0;
for(int i=0;i<n;i++){
if(s[i]=='('){
open++;
}else if(s[i]==')'){
open--;
if(open<0){
open=0;
continue;
}
}
str+=s[i];
}
open=0;
string s2="";
for(int i=n-1;i>=0;i--){
if(str[i]==')'){
open++;
}else if(str[i]=='('){
open--;
if(open<0){
open=0;
continue;
}
}
s2=s2+str[i];
}
reverse(s2.begin(),s2.end());
return s2;
}
};
Leetcode Submission getting wrong
The length of str may be less than one of s, but you are using the length of s while iterating within str. You must use correct length.
string s2="";
n = str.length(); // add this
for(int i=n-1;i>=0;i--){

Segmentation fault and dynamic memory handling

Ok, two questions.
first of all
Q1. I allocated sufficient memory at run time, still after running case 6 two times in a row, the s1 prints garbage, and on running case 6 for a third time the value of s1 disappeared
the first image shows the garbage value at the end of string
[the second image shows the string 1 has disappeared][2]
Q2. the STCPY( COPY FUCTION) is not working properly, its showing segmentation fault, but again, I reallocated sufficient memory.( I need to copy s2 to s1, so I reallocated L2(string 2's length) to s1 so that there won't be memory wastage)
segmentation fault
here's the code:
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int STRLEN(char* S){
int i=0;
while(S[i] != '\0'){
i++;
}
return i;
}
int SUBSTR(char* str1, char* str2){
//string str1;
//string str2;
int L1=0,L2=0;
int i,j,flag=0;
int count=0;
/*cout<<"\nEnter main string greater characters(str1) : ";
cin>>str1;
cout<<"\nEnter phrase to find (str2) : ";
cin>>str2;
*/
L1 = STRLEN(str1); //calculate legth of strings
L2 = STRLEN(str2);
for(i=0;i<L1;i++){
count = 0;
flag = 0;
for(j=0;j<L2;j+=1){
if(str1[i]==str2[j])
{
//good
if(j==L2) //successful phrase's each character
traversed
{
break;
}
i++;
count++;
//j++;
}
else
{
break;
}
} //terminate inner for loops
{
i -= count; //i was incremented explicitly in
inner loop. for normal operation,
} // i has to be decremented by equal
no. of increments in inner loop
if(j==L2) //flag for successful traversing of phrase 2
in string 1
{
flag = 1;
break;
}
}
if(flag == 1)
{
cout<<"\nSUBTRING PRESENT AT "<<(i+1);
}
return 0;
}
int STREQL(char* str1, char* str2){
int flag = 0;
int L1=0,L2=0;
int i,j;
int count=0;
/* cout<<"\nEnter first word : ";
cin>>str1;
cout<<"\nEnter second word : ";
cin>>str2;*/
char* p1;
char* p2;
p1 = str1;
p2 = str2;
while(*(p1) != '\0')
{
if(*(p1) == *(p2))
{
//good
p1++;
p2++;
}
else{
flag = 1;
break;
}
}
if(flag == 1 )
{
cout<<"\n STRINGS ARE NOT EQUAL";
}
else{
cout<<"\n STRINGS ARE EQUAL";
}
return 0;
}
int STCPY(char* s1, char* s2){
int L2 = STRLEN(s2);
int L1 = STRLEN(s1);
cout<<"\nPASS 1";
char* s3 = (char*)realloc(s1,L2); //Note :- s3 and s1 point to
same memory location
cout<<"\nPASS 2";
while(s2 != '\0')
{
*s3 = *s2;
s3++;
s2++;
}
cout<<"\nPASS 3";
s3 -= L2;
s2 -= L2;
cout<<"\n STRING 1 = "<<s1;
cout<<"\n STRING 2 = "<<s2;
return 0;
}
int STRREV(){
return 0;
}
int STRLEN(char* str1, char* str2){
int L1=0,L2=0;
L1=STRLEN(str1);
L2=STRLEN(str2);
cout<<"\nSTRING 1 LENGTH = "<<L1;
cout<<"\nSTRING 2 LENGTH = "<<L2;
return 0;
}
int STRCAT(char* s1, char* s2)
{
int L1=0,L2=0;
int i,j;
L1=STRLEN(s1);
L2=STRLEN(s2);
//cout<<"\nSTRING 1 LENGTH = "<<L1;
//cout<<"\nSTRING 2 LENGTH = "<<L2;
char* s3 = (char*)realloc(s1,(L1+L2));
int cnt=0;
for(i=L1,s3 = s3+L1; *s2 != '\0'; i++)
{
*s3 = *s2;
s2++;
s3++;
cnt++;
}
s3 = s3-cnt-L1;
s2 = s2-cnt;
//cout<<"\nConcatenated string s3 = "<<s3;
//cout<<"\nConcatenated string s1 = "<<s1;
cout<<"\nSTRING 1 = "<<s1;
cout<<"\nSTRING 2 = "<<s2;
return 0;
}
int main(){
int i,j,choice;
char* s1;
char* s2;
cout<<"\nEnter string : ";
s1 = (char*)malloc(50);// ok i made this 50 bytes instead of 10
cin.getline(s1,50); // cause u guys arguing, but still that doesn't change the output
//cout<<s1;
cout<<"\nEnter string : ";
s2 = (char*)malloc(50);
cin.getline(s2,50);
//cout<<s2;
cout<<"\n------------MENU------------";
cout<<"\n1.SUBSTRING FIND";
cout<<"\n2.EQUAL CHECK";
cout<<"\n3.COPY STRING";
cout<<"\n4.REVERSE";
cout<<"\n5.STRING LENGTH";
cout<<"\n6.STRING CONCATENATION";
cout<<"\n7.EXIT";
cout<<"\n----------------------------";
do{
cout<<"\n\nEnter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
SUBSTR(s1, s2);
break;
case 2:
STREQL(s1, s2);
break;
case 3:
STCPY(s1, s2);
break;
case 4:
STRREV();
break;
case 5:
STRLEN(s1, s2);
break;
case 6:
STRCAT(s1, s2);
break;
case 7:
break;
}
}while(choice != 7);
return 0;
}
Replace everything under "PASS 2" log to this:
while(*s2 != '\0')
{
*s3 = *s2;
s3++;
s2++;
}
Observe that s2 != '\0' means basically: s2 != nullptr which is never true. That's why you get segmentation fault.
A C string is ended with a final \0. So the memory footprint is strlen(str) + 1 byte.
The problem with your STRCAT function is that you forgot to add space for the final \0 (s3 = realloc(s1, L1+L2 +1), and you also forgot to add the final \0 (s3[L1+L2] = 0).
idem for your STCPY function, + s2 != 0 to replace with *s2 != 0

C++ find special char and move to the end of a string

I am currently a student taking C++. My issue is that my nested if statement does not find the special chars if they are at the end of the word. From what I can tell, it does not run the function at all. If anyone has any idea what is wrong that will be great!
#include <iostream>
#include <string>
using namespace std;
bool isVowel(char ch);
string rotate(string pStr);
string pigLatinString(string pStr);
bool specialChar(char ch);
int main() {
string str, str2, pigsentence, finalsentence, orgstr, end;
int counter, length, lengtho;
counter = 1;
cout << "Enter a string: ";
getline (cin, str);
cout << endl;
orgstr = str;
//Add in option to move special chars
string::size_type space;
do {
space = str.find(' ', 0); //Finds the space(s)
if(space != string::npos){
str2 = str.substr(0, space); //Finds the word
if(specialChar(str[true])) { //Finds special char
end = str.substr(space - 1); //Stores special char as end
cout << end << endl; //Testing end
str.erase(space - 1); //Erases special car
}
str.erase(0, space + 1); //Erases the word plus the space
pigsentence = pigLatinString(str2); //converst the word
finalsentence = finalsentence + " " + pigsentence + end; //Adds converted word to final string
}else {
length = str.length();
str2 = str.substr(0, length); //Finds the word
if(specialChar(str[true])) { //Finds special char
end = str.substr(space - 1); //Stores special char as end
cout << end << endl; //Testing end
str.erase(space - 1); //Erases special car
}
str.erase(0, length); //Erases the word
pigsentence = pigLatinString(str2); //converst the word
finalsentence = finalsentence + " " + pigsentence + end; //Adds converted word to final string
counter = 0;
}
}while(counter != 0); //Loops until counter == 0
cout << "The pig Laten form of " << orgstr << " is: " << finalsentence << endl;
return 0;
}
The function that lists the specialChars is below
bool specialChar(char ch) {
switch(ch) {
case ',':
case ':':
case ';':
case '.':
case '?':
case '!':
return true;
default:
return false;
}
}
I do have other functions but they are working and just convert a word to piglatin.
your isSpecialChar takes a character as argument so str[index] would be something you could pass but instead you write str[true] which is not correct. If you want to check if there is a specialChar in your string you need to loop through the whole string and check each character.
It seems as if you want to split up a string into words so you could write something like this
char Seperator = ' ';
std::istringstream StrStream(str);
std::string Token;
std::vector<std::string> tokens;
while(std::getline(StrStream, Token, Seperator))
{
tokens.push_back(Token);
}
now that you have the words in a vector you can do whatever what you want
with them like checking for a special char
for (int i = 0; i < tokens.size(); ++i)
{
std::string& s = tokens[i];
for (int j = 0; j < s.length(); ++j)
{
if ( specialChar( s[j] )
{
...do whatever...
}
}
}
You're using true as your array index when passing arguments to the specialChar() function! Surely that isn't what you meant to do. Fix that and you might see some improvement.
Think of the function call broken down a little, like this, to help you keep track of the types:
// takes a char, returns a bool, so....
bool specialChar( char in )
{ ... }
for( int i = 0; i < str.size(); i++ )
{
char aChar = str[i];
// ...pass in a char, and receive a bool!
bool isSpecial = specialChar(aChar);
if( isSpecial )
{
...
}
}
There's generally no harm in writing the code in a way that makes it clearer to you what's going on, when compiled and optimised it will all likely be the same.

Strings with whitespace in a list?

I have this function sentanceParse with a string input which returns a list. The input might be something like "Hello my name is Anton. What's your name?" and then the return value would be a list containing "Hello my name is Anton" and "What's your name?". However, this is not what happens. It seems as if the whitespaces in the sentences are treated like a separator and therefore the return is rather "Hello", "my", "name" etc instead of what I expected.
How would you propose I solve this?
As I am not a 100% sure the problem does not lie within my code, I will add that to the post as well:
Main:
list<string> mylist = sentanceParse(textCipher);
list<string>::iterator it;
for(it = mylist.begin(); it != mylist.end(); it++){
textCipher = *it;
cout << textCipher << endl; //This prints out the words separately instead of the entire sentances.
sentanceParse:
list<string> sentanceParse(string strParse){
list<string> strList;
int len = strParse.length();
int pos = 0;
int count = 0;
for(int i = 0; i < len; i++){
if(strParse.at(i) == '.' || strParse.at(i) == '!' || strParse.at(i) == '?'){
if(i < strParse.length() - 1){
while(i < strParse.length() - 1 && (strParse.at(i+1) == '.' || strParse.at(i+1) == '!' || strParse.at(i+1) == '?')){
if(strParse.at(i+1) == '?'){
strParse.replace(i, 1, "?");
}
strParse.erase(i+1, 1);
len -= 1;
}
}
char strTemp[2000];
int lenTemp = strParse.copy(strTemp, i - pos + 1, pos);
strTemp[lenTemp] = '\0';
std::string strAdd(strTemp);
strList.push_back(strAdd);
pos = i + 1;
count ++;
}
}
if(count == 0){
strList.push_back(strParse);
}
return strList;
}
Your implementation of sentence parse is wrong, here is a simpler correct solution.
std::list<std::string> sentence_parse(const std::string &str){
std::string temp;
std::list<std::string> t;
for(int x=0; x<str.size();++x){
if(str[x]=='.'||str[x]=='!'||str[x]=='?'){
if(temp!="")t.push_back(temp);//Handle special case of input with
//multiple punctuation Ex. Hi!!!!
temp="";
}else temp+=str[x];
}
return t;
}
EDIT:
Here is a full example program using this function. Type some sentences in your console, press enter and it will spit the sentences out with a newline separating them instead of punctuation.
#include <iostream>
#include <string>
#include <list>
std::list<std::string> sentence_parse(const std::string &str){
std::string temp;
std::list<std::string> t;
for(int x=0; x<str.size();++x){
if(str[x]=='.'||str[x]=='!'||str[x]=='?'){
if(temp!="")t.push_back(temp);//Handle special case of input with
//multiple punctuation Ex. Hi!!!!
temp="";
}else temp+=str[x];
}
return t;
}
int main (int argc, const char * argv[])
{
std::string s;
while (std::getline(std::cin,s)) {
std::list<std::string> t= sentence_parse(s);
std::list<std::string>::iterator x=t.begin();
while (x!=t.end()) {
std::cout<<*x<<"\n";
++x;
}
}
return 0;
}
// This function should be easy to adapt to any basic libary
// this is in Windows MFC
// pass in a string, a char and a stringarray
// returns an array of strings using char as the separator
void tokenizeString(CString theString, TCHAR theToken, CStringArray *theParameters)
{
CString temp = "";
int i = 0;
for(i = 0; i < theString.GetLength(); i++ )
{
if (theString.GetAt(i) != theToken)
{
temp += theString.GetAt(i);
}
else
{
theParameters->Add(temp);
temp = "";
}
if(i == theString.GetLength()-1)
theParameters->Add(temp);
}
}