Reverse each character in a string except special characters (e.g. "?") [closed] - c++

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
For example : how are you? ----> woh era uoy?
This is my code, i got it worked but the question mark is besing reversed too.
How can i make it remained intact?
#include <iostream>
using namespace std;
int main()
{
string ch;
while(cin >> ch)
{
for(int i = ch.length() - 1; i >= 0; i--)
{
cout << ch[i];
}
cout << " ";
}
return 0;
}

Your chosen input method (cin >> ch) automatically splits the input into separate words.
Like Jerry Coffin said in his answer, you have to skip over punctuation etc to find to alpha characters to swap. Roughly like this:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
string ch;
while (cout << "String? " && cin >> ch)
{
cout << "Input: <<" << ch << ">>\n";
const char *bp = ch.c_str();
const char *ep = ch.c_str() + ch.length() - 1;
const char *sp = ch.c_str();
while (sp < ep)
{
while (sp < ep && (*sp != ' ' && !isalpha(*sp)))
sp++;
while (sp < ep && (*ep != ' ' && !isalpha(*ep)))
ep--;
char c = *sp;
ch[sp-bp] = *ep;
ch[ep-bp] = c;
sp++;
ep--;
}
cout << "Output: <<" << ch << ">>\n";
}
cout << endl;
return 0;
}
Sample dialogue
String? How are you?
Input: <<How>>
Output: <<woH>>
String? Input: <<are>>
Output: <<era>>
String? Input: <<you?>>
Output: <<uoy?>>
String? Pug!natious=punctuation.
Input: <<Pug!natious=punctuation.>>
Output: <<noi!tautcnu=psuoitanguP.>>
String?
You can tweak it from here. I'm far from claiming this is idiomatic C++; the use of const char * in the middle shows my C background.

Start from the beginning of the string, and scan forward until you find a letter. The scan backwards from the end until you find a letter. Swap them. Continue until the two positions meet.
Note: above I've used "letter", but all I really mean is "one of the characters that should be reversed." You haven't defined very precisely which characters should be swapped and which shouldn't, but I'm assuming you (or your teacher) has a reasonably specific definition in mind.

Try using array and scanning each letter to see if there is a question mark. If there is, move it to the last place of the array.

simple solution or hack to solve this case alone. if there are more cases comment it lets solve it together.
#include <iostream>
using namespace std;
int main()
{
string ch;
while(cin >> ch)
{
int flag = 0;
for(int i = ch.length() - 1; i >= 0; i--)
{
if(ch[i] != '?')
cout << ch[i];
else
flag = 1;
}
if(flag)
cout << "?";
else
cout << " ";
}
return 0;
}

Related

How can I replace every alphabetical lower case letter in a string with its opposite alphabetical lower case letter 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
I would like to find the opposite letter using for loop. Also, I would like to note that I am trying to find the opposite letter. For example, replacing "a" with "z", "b" with "y"...
For example, the user inputs this: "3 feg", and the output from this program will be: "uvt". Also, my constraint is 1<=n<=100. The input format is "n input_string_of_length_n", and the output format is "encrypted_string_of_length_n". As a new beginner to programming, I am lost and I do not know how to solve this. Any help will be very much appreciated.
This is my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
`int` user_input_number;
string user_input_text;
cout << "Type: ";
cin >> user_input_number;
cout << "Type: ";
cin >> user_input_text;
for(char i = 'a'; i <= 'z'; i++)
{
cout << << endl;
}
return 0;
}
Here is one solution using ASCII arithmetic:
string s = "abc";
for(int i = 0; i < s.length(); i++){
s[i] = 219 - s[i];
}
cout << s; // "zyx"
The reason it works is that all ASCII characters are between 0 and 127, and this way the values loop back around
// Example program
#include <iostream>
#include <string>
#include <map>
using namespace std;
string encrypt(int n, string s) {
map<char, int> alphabetMap = { };
string alpha = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < 26; i++){
alphabetMap.insert({alpha[i],i});
}
string coded = "";
for (int i = 0; i < n; i++) {
int index = alphabetMap[s[i]];
coded += alpha[25 - index];
}
return coded;
}
int main()
{
int n = 0;
string s = "";
cout << "Enter n and string: " ;
cin >> n >> s;
cout << encrypt(n,s) << endl;
}

Convert lowercase to uppercase in a string [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 3 years ago.
Improve this question
The new typist in the printing cell is typing carelessly the jobs assigned. The typist while was supposed to type all the characters in upper case, has got in lower cases too. Your duty is to verify if all the characters are in upper case and do so if not. Also, notify how many mistakes the typist did.
Input bEGIN
Output BEGIN 1
I am getting wrong answer in some of the cases please help i am beginner
n=length of string
1<=n<=50
int main() {
string s;
cin >> s;
int ans = 0;
for (auto &c : s) {
if (islower(c)) {
ans++;
c = toupper(c);
}
}
cout << s;
cout << endl;
cout << ans;
return 0;
}
I think it includes spaces too, so instead of using >> operator use getline(cin,string), as >> gets terminate when whitespace is occurred.
#include <iostream>
using namespace std;
int main() {
string s;
getline(cin,s);
int ans = 0;
for (auto &c : s) {
if (islower(c)) {
ans++;
c = toupper(c);
}
}
cout << s;
cout << endl;
cout << ans;
return 0;
}
This might be a solution to other test cases.
This should work:
#include<stdio.h>
#include<iostream>
#include<string>
using namespace std;
int main() {
string s;
getline(cin,s);
int ans = 0;
for (auto &c : s) {
if (islower(c)) {
ans++;
c = toupper(c);
}
}
cout << s;
cout << endl;
cout << ans;
return 0;
}

Element counting issue [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 6 years ago.
Improve this question
#include <iostream>
using namespace std;
int countLetters(char text[], char letter);
int main()
{
char letter;
cout << "Enter a letter: ";
cin >> letter;
cin.ignore();
char text[1024];
cout << "Enter text: ";
cin.getline(text, 1024);
int letterCount = countLetters(text, letter);
cout << "Number of '" << letter << "'s: " << letterCount << endl;
return 0;
}
int countLetters(char text[], char letter)
{
int letterCount = 0;
for (int i = 0; i <= text[i]; i++)
{
if (letter == text[i])
letterCount++;
}
return letterCount;
}
This code, as written, is designed to ask the user for, first, the letter they want to search for in a line of text. Second, it will ask the user to input the line of text they want to have searched. Finally, it will spit out how many letters there are in the specific line of text they input.
My specific error lies here: when user asks for 'e' in "CS 124 - Introduction to Software Development", program only declares that there is one 'e' . I'm unsure what's wrong, because when you run the program and input 'o' while asking to search the exact same line of text, you get the proper number of 'o' values returned, 4.
Any ideas as to what my error is and why it glitches when searching for 'e' ?
Your for condition is wrong, the for loop should continue while i is less than text's length not the value of text[i]. Since this is C++ you should use strings not character arrays, why make it harder on yourself?
The code below is a C++ approach, note that my C++ is a bit rusty and the code might contain errors.
#include <iostream>
#include <string>
using namespace std;
int countLetters(string text, char letter);
int main() {
char letter = ' ';
string text;
cout << "Enter a letter: ";
cin >> letter;
cin.ignore();
cout << "Enter text: ";
getline(cin, text); // use 'getline(cin, text)' instead of 'cin >> text'
int letterCount = countLetters(text, letter);
cout << "Number of '" << letter << "'s: " << letterCount << endl;
return 0;
}
int countLetters(string text, char letter) {
int letterCount = 0;
for (int i = 0; i < text.size(); i++) {
if (letter == text[i]) {
letterCount += 1;
}
}
return letterCount;
}
change the condction
i <= text[i]
to
text[i] != '\0'

Un-mash a string in C++ using recursion [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
Part A: Have a user input a string. Then display this string smashed up as follows: display the first character in the string, then the last, then the second, then the second to last, then the third... So if the string is “abcdef”, it will display:
afbecd (input “abcdef”)
12345 --> 15243
123456 --> 162534
Part B: Now, unmash the above strings.
i.e 162534 -->123456
I got part A to work.
#include <iostream>
using namespace std;
void mash(string s);
int main()
{
string sequence;
cout << "Enter a sequence: ";
getline(cin, sequence);
mash(sequence);
}
void mash(string s)
{
int a = s.length();
if (a == 0)
{
return;
}
if (a == 1)
{
cout << s;
return;
}
cout << s[0];
if(a>1)
{
cout << s[a - 1];
s = s.substr(1,a-2);
mash(s);
}
}
but I have no clue how to approach part B. I guess I can try to print out the characters in the even position, say in the string 162534, thus I will get 123. Then I guess I can try to print out the odd position characters from the last one up to the first one, i.e, 456. Combining these two will get the original strings but I have no clue how to use recursion to solve part B.
Here is a hint. So unmash(string s) should first print the first character s[0], then unmash(s.substr(2, length - 2)), then s[1]. Of course, you also need to check if length <= 2 need to treat that differently.
Here is my answer an it works perfectly thanks to all of the members of SO who helped me.
#include <iostream>
using namespace std;
void unmash(string s);
int main()
{
string sequence;
cout << "Enter a sequence: ";
getline(cin, sequence);
unmash(sequence);
}
void unmash(string s)
{
int a = s.length();
if (a == 0)
{
return;
}
if (a == 1||a == 2)
{
cout << s;
return;
}
cout << s[0];
if(a>1)
{
unmash(s.substr(2));
cout << s[1];
}
}

Preventing user from inputting certain chars 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 8 years ago.
Improve this question
I'm quite new to c++ so please understand that my question may be silly.
I need to create a function which takes from the user a table and fills it with only specific characters. Let's say that the user needs to input his name. If the user inputs a charater from A to Z (or a to z) the character should be displayed on the screen and in that case- everything is fine. The problem is- when the user inputs a forbidden character (for instance 1-9) this shouldn't be displayed on the screen and the cursor should stay in the same position).
Do you guys know how to do this?
May be you can use this to do your job:
char ch;
while(ch = getch())
{
if((ch>='A' && ch<='Z') || (ch>='a' && ch<='z'))
{
cout << ch;
}
}
This will print only [A-Z][a-z]. You can also store your required char to use further.
On Windows you can use conio.h.
Also, you can overload the istream::operator>> function to make solution more elegant and easy to use:
Complete example:
#include <iostream>
#include <conio.h>
using namespace std;
struct person_t
{
string name;
string last_name;
};
// This is the function you're looking for.
void get_filtered_string(string &str)
{
char c;
str = "";
do
{
c = _getch();
if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'))
{
putchar(c); // 1
str.push_back(c);
}
} while (c != '\r'); // 2
}
istream &operator>>(istream &stream, person_t &person)
{
string str = "";
cout << "Enter name: ";
get_filtered_string(str);
person.name = str;
cout << endl;
cout << "Enter last name: ";
get_filtered_string(str);
person.last_name = str;
cout << endl;
return stream;
}
int main()
{
person_t person;
cin >> person;
cout << person.name.c_str() << " " << person.last_name.c_str() << endl;
return 0;
}
Output character to screen.
In Windows when you hit Enter you're introducing two characters '\r' and '\n' in that order. Thats why we check here for '\r'.