C++ Finding Specific characters in a string - c++

Writing a program that asks the user to insert a word. The word gets stored in a string, then the user is asked to insert the position of a character in the word they want displayed. IE. User inputs Peanuts, User then inputs 4, Output is N

You can do it in this way:
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string s = "thisisastring";
int position = 0;
cin>>position;
cout<<s.at(position);
return 0;
}
If you enter 4 it will output 'i' because the starter index of the string is 0.. if you want to output the 4^ character you need to to use cout<<s.at(position-1);
if you enter '0' or a number over than string.lenght() this code generate an error, if to want to prevent this issue you have to run this:
#include <iostream>
#include <string.h>
using namespace std;
int main() {
string s = "thisisastring";
int position = 0;
do{
cin>>position;
}while(position <=0 || position > s.length());
cout<<s.at(position);
return 0;
}

Related

How to extract substring by using start and end delimiters in C++

I have a string from command line input, like this:
string input = cmd_line.get_arg("-i"); // Filepath for offline mode
This looks like a file as below:
input = "../../dataPosition180.csv"
I want to extract out the 180 and store as an int.
In python, I would just do:
data = int(input.split('Position')[-1].split('.csv')[0])
How do I replicate this in C++?
Here's a (somewhat verbose) solution:
#include <string>
#include <iostream>
using namespace std;
int main() {
string input = "../../dataPosition180.csv";
// We add 8 because we want the position after "Position", which has length 8.
int start = input.rfind("Position") + 8;
int end = input.find(".csv");
int length = end - start;
int part = atoi(input.substr(start, length).c_str());
cout << part << endl;
return 0;
}
#include <string>
#include <regex>
using namespace std;
int getDataPositionId (const string& input){
regex mask ("dataPosition(\\d+).csv");
smatch match;
if (! regex_search(input, match, mask)){
throw runtime_error("invalid input");
}
return std::stoi(match[1].str());
}

How can I go through a string entered by the user and return the same string 7 characters ascii forward?

For example, if I introduce hello, the program through the ASCII table will return the same but character 7 letters forward: 'hello' -> 'olssu'.
Thanks in advance.
I have tried this but it obviously doesn't work:
#include <iostream>
using namespace std;
int main()
{
int asciiValue=65;
string pass;
cout<<"introduce la contraseña"<<endl;
cin>>pass;
char character = char(asciiValue+7);
for(int a=0;a<pass.length();a++){
cout<<character;
cout<<pass[a];
}
return 0;
}
In your example, 'hello' would become 'olssv' moving ahead by 7 positions.
The code for achieving this would look like this:
#include <iostream>
#include <string>
using namespace std;
int main() {
string inputString;
cin>>inputString;
// iterate through the string
for(int i=0; i< inputString.length(); i++) {
// for each character, get its ASCII value
// in C++, if you simply parse a character to an int
// you will get the ASCII value
int asciiValue = int(inputString[i]);
// add 7 to the ascii value and print it as a char
cout<<char(asciiValue + 7);
}
return 0;
}

Understanding String::Find In C++

I've been given a programming task that involves taking away certain letters in a string. I was trying out different ways to do this when I found the public member function string find. To put it short I was testing out the function via this program :
#include <iostream>
#include <string>
using namespace std;
int main()
{
string Word = "Applejuice";
cout<<Word.find("e")<<endl;
return 0;
}
So when I put in a letter such as "e" I get the number 4 which confuses me because I thought the function will count all the letters in that specific word such as apple juice. Also, when I use a letter that is not used in that word I get numbers like 18446744073709551615 for example when I put in X for e in the code above.
Could someone explain why this is happening, please?
string.find() will return the position of the first character of the first match.
If no matches were found, the function returns string::npos.
Therefore the number (18446744073709551615) you are getting is the string::npos
If you want to search for an only a single character in the string you can use the following code
#include <iostream>
#include <string>
using namespace std;
// Function that return count of the given
// character in the string
int count(string s, char c)
{
// Count variable
int res = 0;
for (int i=0;i<s.length();i++)
// checking character in string
if (s[i] == c)
res++;
return res;
}
// Driver code
int main()
{
string str= "Applejuice";
char c = 'e';
cout << count(str, c) << endl;
return 0;
}
If you want to avoid some random large values as output i.e. string::npos you can just add check for it like following:
if(Word.find("e") != string::npos)
{
...
}
Method find from class string return the position of the first character of the first match. Return type of find is size_t and since size_t is unsigned integral so if no match were found return string::nopos so you should compare the outputof find with string::nopos.
if(Word.find("e") != string::nopos)
{
...
}

Keep output and input from alternating?

I am very new to coding, and have been practicing with some easy problems at codeforces.com. I was working on this problem, but it seemed to be asking for the input (all at once) yielding the output (all at once). I can only figure out how to get one output at a time.
Here are the basic instructions for the problem:
Input
The first line contains an integer n (1 ≤ n ≤ 100). Each of the following n lines contains one word. All the words consist of lowercase Latin letters and possess the lengths of from 1 to 100 characters.
Output
Print n lines. The i-th line should contain the result of replacing of the i-th word from the input data.
Examples
input
4
word
localization
internationalization
pneumonoultramicroscopicsilicovolcanoconiosis
output
word
l10n
i18n
p43s
Here is my code:
#include <iostream>
#include <string>
using namespace std;
void wordToNumbers(string word){
int midLetters = word.length();
char firstLetter = word.front();
char lastLetter = word.back();
cout <<firstLetter <<(midLetters-2) <<lastLetter <<endl;
}
int main(){
string wordInput;
string firstNum;
getline(cin,firstNum);
int i = stoi(firstNum);
for(i>=1; i--;){
getline(cin,wordInput);
if (wordInput.length() > 10){
wordToNumbers(wordInput);
} else {
cout <<wordInput <<endl;
}
}
return 0;
}
it's perfectly fine to read and print output for the lines one by one.
Exactly your solution accepted: http://codeforces.com/contest/71/submission/16659519
I'm also a beginner in c++. My idea would be to save every line first in a buffer and then write everything to std::cout.
I use a std::vector as the buffer, cause IMO it is simple to understand and very useful in many cases. Basically it is a better array. You can read more about std::vector here.
#include <iostream>
#include <string>
//for use of std::vector container
#include <vector>
using namespace std;
void wordToNumbers(string word){
int midLetters = word.length();
char firstLetter = word.front();
char lastLetter = word.back();
cout <<firstLetter <<(midLetters-2) <<lastLetter <<endl;
}
int main(){
string wordInput;
string firstNum;
//container for buffering all our strings
vector<string> bufferStrings;
getline(cin,firstNum);
int i = stoi(firstNum);
//read line by line and save every line in our buffer-container
for(i>=1; i--;){
getline(cin,wordInput);
//append the new string to our buffer
bufferStrings.push_back(wordInput);
}
//now iterate through the buffer and write everything to cout
for(int index = 0; index < bufferStrings.size(); ++index) {
if (bufferStrings[index].length() > 10){
wordToNumbers(bufferStrings[index]);
} else {
cout <<bufferStrings[index] <<endl;
}
}
return 0;
}
Probably this is not the best or most beautiful solution, but it should be easy to understand :)

Wrong answer in c++

You are given a DNA sequence, and few enzymes. Suppose, a DNA sequence goes like this : ATGCTGCTATGCATGCAGTGACT, and you are given enzymes which can remove AT and GC sequences. Thereby, you need to remove all occurrences of AT from the DNA first and then reform the DNA and apply the next enzyme to remove all occurrences of GC. The output of the problem would be the string you get at last reforming the pieces which are not removed by these enzymes.
Input
The first line of input consists of an integer n that denotes the number of enzymes. The first line has the DNA sequence. The next T lines has the input B1, B2, B3... Bn.
Output
For given input DNA sequence, output a single line containing the final reformed DNA that is formed by repeatedly removing all the occurrences of B1, B2, B3... Bn from A.
In case the DNA is completely consumed print 0 to indicate that there is no DNA left.
Constraints
1 <= n <= 10
Example 1:
Input:
2
ATACGCATGACGATGCATGCAGCAT
ATA
GC
Output:
CATGACGATATAAT
Example 2:
Input:
3
ATGCATGCATCGACTCAGCATCAGCATCGACTA
TG
GC
AT
Output:
ACACCGACTCACACGACTA
My code:
I tried solving it using string in c++, I am getting :
terminate called after throwing an instance of 'std::out_of_range'
what():basic_string::erase()
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <math.h>
#include <vector>
#include <set>
#include <stdlib.h>
#include <string.h>
#include <queue>
#include <stack>
#include <assert.h>
#include <limits.h>
using namespace std;
int main() {
string str, str1;
int n;
scanf("%d", &n);
cin >> str;
while (n--) {
cin >> str1;
int len = str1.length();int len1=str.length();
for (int i = 0; i < len1; i++) {
int found = str.find(str1);
str.erase(found, found + len);
}
}
cout << str;
return 0;
}
Three main problems:
Number one, out of range exception on string::erase.
Fixed by testing that find actually returned a value:
if (found!=std::string::npos)
Number two, searching correctly.
Fixed by keeping track of found (it's also a size_t not an int) and searching from the next location:
found = str.find(str1,found);
Number three, using string::erase properly.
Fixed by using length of substring to erase, not length + position:
str.erase(found,len);
I still haven't added any input validation to your code. You should really think about doing that yourself.
Final code:
(ideone)
#include <string>
#include <iostream>
int main()
{
std::string str;
std::string str1;
int n;
std::cin>>n;
std::cin>>str;
while(n--)
{
std::cin>>str1;
int len = str1.length();
size_t found = 0;
for(unsigned int i=0;i<str.length();i++)
{
found = str.find(str1,found);
if (found!=std::string::npos)
{
str.erase(found,len);
}
else
{
break;
}
}
}
std::cout<<(str.length()?str:"0");
return 0;
}
idone output for each example input (I've added your example outputs in between the /* */ marks):
Success time: 0 memory: 3476 signal:0
CATGACGATATAAT
/*CATGACGATATAAT*/
Success time: 0 memory: 3476 signal:0
ACACCGACTCACACGACTA
/*ACACCGACTCACACGACTA*/