Concatenating characters of a string in a specific permutation - c++

I am trying to code a C++ program that takes a 5 character long string and then prints out the string with a new permutation with this order: 1st character, 3rd character, 5th character, 2nd character, 4th character. My code is as follows:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string key;
string p10;
cout << "Enter the five characters long string: ";
cin >> key;
p10 = key[0] + key[2] + key[4] + key[1] + key[3];
cout << p10 << endl;’
system(“pause”);
return 0;
}
The output (p10) is a random Greek letter every time I run it.
Please help!

The problem here is that when you use [] on a string, you're not getting back another string, but a single char. A char is actually just a small integer number (think character code), and if you use the + operator with them, it'll add the numbers together. You'll end up with a more or less random character code, which is why you get greek letters.
If you want to keep the structure of the code as close to the original as possible, you can use substr to get "one character strings" instead of plain chars:
key.substr(0, 1) + key.substr(2, 1) + ...
The 1 signifies that you want one character from the specified offset.
Another way is to first construct a char array out of the characters and then turn it into a string:
char p10_arr[] = { key[0], key[2], ... };
string p10(arr, sizeof(arr));
And perhaps the nicest and most concise way is to use the initializer list syntax:
string p10 { key[0], key[2], ... };

Related

Destiny Number Calculator

hi can someone please help me to complete this code in c++ if you may interested
here is the project which will print the position of a char in string, this is very close to my task but not exactly
here is the problem: program only print the position of a char, for example for letter 'S' it prints 18 because it sits at position 18, how i can change this program which instead of that, the program print my values, i don't really care about the position i care about the value that should return or store, the value i specify,
program for sam prints
S=18
A=1
M=13
instead i want it know for letter S print 7 or store 7, i mean instead of caring about position should care about the value at the final result which i explained
all 26 alphabet as you see has a value base on the position i want that pos value to be changed and result other pos int value
#include<iostream>
#include<string>
#include<exception>
#include <cstdlib>
#include<stdio.h>
#include <cctype>
using namespace std;
int main()
{
const std::string alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << "Please enter your the name:";
std::string text;
std::cin >> text;
// convert all lower case characters to upper case
for (char& c : text)
c = std::toupper(c);
// Lookup character
for (char& c : text) // for each character c in text
{
const auto pos = alpha.find(c);
if (pos != std::string::npos) // if found (if the character is an alpha character)
// note: non-alpha characters are ignored
{
const int value = pos + 1; // +1 because position of 'A' is 0, value of 'A' is 1
// Print the character and the position
cout << c << "=" << pos << endl;
}
}
}
It depends on what kind of result you're looking for. If you're looking to return values in the range of the alphabet, then just rearrange the letters to match what you want them to return.
If you're looking for something with higher or lower values, then take a look at building a map and accessing the key value pairs. https://en.cppreference.com/w/cpp/container/map

Converting a C string to individual integers

This exercise asks to take a input as a character array of number then add up the digits of the number.
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int main() {
//Input a series of single digit numbers
char numbers[] = "a";
cout << "Input a series of single digit numbers." << endl;
cin >> numbers;
//convert the character array into a int array.
int sum = 0;
for (int i = 0; i < size; i++) {
sum += atoi(numbers[i]);
}
cout << "Sum of digits: " << sum;
return 0;
}
The atoi function, by my understanding, converts only whole character arrays (C strings) at a time, and I guess I cant step through the array, but it seems like this should work. My other option was to convert the Cstring to one large integer, then use the length of the string to step through and calculate the digits in each position but that's probably more inefficient that I could be making it.
What would you use to find single digits as ints for a character array?
char numbers[] = "a";
This creates an array of 2 char items. That's not sufficient for anything reasonable. Use a std::string instead.
cin >> numbers;
Better use std::getline from the <string> header.
sum += atoi(numbers[i]);
atoi takes a string as argument, not a single char. You want the sum of the digits, not the sum of the number values you get by applying atoi to all right substrings of the specification.
For a digit character ch, the corresponding digit value is ch - '0'.

Calculate occurance of each character in a string without using count in C++

Here is my code:
#include <iostream>
#include <string>
using namespace std;
void calc(string s){
for(int i = 0;i < s.size();++i){
int count = 1;
for(int j = i + 1;j <s.size();++j){
if(s[i] == s[j]){
count += 1;
}
}
cout << s[i] <<"(" << count << ")" << " ";
}
}
int main(){
string str;
while(cin >> str){
calc(str);
}
}
Everything works fine, except that I want to iterate through unique characters in string and I don't know how to implement this.
Can you help me with it?
There are many ways you can do this. Here are a few suggestions:
Modify the code you have written so that before you count up how many times a character appears after the current character, you first scan over the characters before you in the string to see if any of them match. If so, skip the current character.
Every time you find a character that matches the current character, replace it with a copy of the first character in the string. Then, whenever you visit a character in the string that isn't in the first position, check if it matches the first character in the string. If so, you've already scanned it. If not, count up its occurrences.
Maintain an auxiliary data structure (an array, a hash table, etc.) mapping characters to their frequencies. Fill in the table by doing one pass over the original string, then iterate over the table, which has unique keys, to print everything out.
Sort the string. Counting how many times each character occurs then boils down to finding the length of each consecutive run of characters in the string.
Option (1) is good if you can't modify the original string and if you're not allowed to use other data structures. Option (2) has excellent time and space requirements if you're allowed to modify the original string. Option (3) is likely the easiest to code up, but uses a bit more space than other approaches. Option (4) is also very easy to code up and, if you use something like heapsort, has good memory usage but is still asymptotically slower than option (2).
Why don't you maintain an auxillary array of 26 length, initialize it to 0 and then increment the corresponding index's value by 1 everytime you encounter a character?
Pseudocode:
auxArray[26] = [0] // 26 length array initialized to zero
for character in string: // loop through every character in the string
auxArray[character - 'a']++; //increment the corresponding index value by 1
print auxArray //print the entire array. [0] will give you count of 'a', and [25] will give you count of 'z'
This is assuming that you have a character String from 'a' to 'z' (All lower case).
In the case where we have an uppercase-lowercase mixture of characters as well, you might similar stuff but instead use an array of 128. In this case, you won't have to subtract 'a' as it was being done to accommodate the indexes with the chars.
auxArray[128] = [0]
for character in string:
auxArray[character]++;
for index in auxArray:
print(((char)index) + " Count is " + auxArray[index])
Another way to do this is with std::map:
std::map<char,int> count;
for (int i = 0; i < s.size(); ++i)
count[s[i]]++;
for (auto iter = s.begin(); iter != s.end(); ++iter)
std::cout << iter->first << “: “ << iter->second << ‘\n’;
Not tested, sorry.

Reading character by character to see if it is a digit

I need help with this if statement. Im trying to read each character to see if it is a number. If it is not a digit then say it is not a number if it is continue reading on to the next character. for example if the user inputs 54gr 21 gr42 134 3f3. the only thing that would cout is 21 and 134.
#include <iostream> // libraries
#include <iomanip>
#include <string>
using namespace std;
int main()
{
char string[80];
// char num[80];
// char good[80];
cout << "enter a string "; // prompting user
cin.getline(string,80); // geting line
// int i = 0;
// int j = 0;
int count = 0;
{
while(string[count] != '\0') {
if(string[count] >= '0' && string[count] <= '9' )
cout << count << endl;
}
++ count;
}
}
I would not try to do this character by character. The problem is that you don't now that 5 is really part of a number until you've read to the end of the string of non-space characters to verify that all the contents are legitimately part of a number.
As such, I think you need/want to break the input up into "words", then check whether each complete word can be converted entirely to a number. You can read "words" with just some_stream >> some_string;
Once you have a "word" you check whether you can convert it entirely to a number. Assuming you want integers, you use strtol to (try to) convert it to a number. That will give you a pointer to the first character it couldn't convert as a number. If that's not the end of the string, then that "word" wasn't a number (even if it started with/contained one or more digits).

Why does my string get empty values appended to it when subtracting characters?

I am attempting to solve a problem from topcoder.com and it's driving me crazy. I am learning C++ after a long break from C and am having trouble with strings.
The purpose of the program is to decode a string of 0s and 1s that has gone through an encryption algorithm that consists of adding each adjacent digit to the digit in question.
So 010111 becomes 112232 (LSB and MSB are considered to have zeros next to them). Below is my algorithm to decode the string:
#include <string>
#include <vector>
#include <iostream>
using namespace std;
class BinaryCode {
public:
vector<string> decode(string message);
};
vector<string> BinaryCode::decode(string message) {
vector<string> decoded(2);
int i;
string myTempString;
myTempString.append("0");
myTempString.append(1,message[0] - myTempString[0]);
for(i=2; i<message.size(); i++) {
myTempString.append(1,message[i-1] - myTempString[i-1] - myTempString[i-2]);
}
decoded[0] = myTempString;
myTempString = "";
myTempString.append("1");
myTempString.append(1,message[0] - myTempString[0]);
for(i=2; i<message.size(); i++) {
myTempString.append(1, message[i-1] - myTempString[i-1] - myTempString[i-2]);
}
decoded[1] = myTempString;
return decoded;
}
int main () {
string message("123210122");
BinaryCode *code = new BinaryCode;
vector<string> result = code->decode(message);
cout << "Decoded strings are "+result[0]+" and "+result[1];
getchar();
return 0;
}
The output is nonsense:
Decoded strings are 01
This is just a guess, since you don't show what output you're getting, but it looks like you're doing math on the character values and ending up with characters in the control range. For example, '1' - '0' is not '1' (character 49), it is 1, or Control-A. This is not printable and will typically be invisible in the output. Similarly, '1' + '2' is 49 + 50, or 99, which is 'c'. C++ is not going to magically convert these characters to integers for you. Hopefully this will give you the information you need to fix your code.
A character is an 8-bit integral type. It has the special property that, when printed, it will appear as the character that matches the ASCII value that it contains.
For example:
int valueAsInt = 65;
char valueAsChar = valueAsInt;
std::cout << valueAsChar << "\n";
valueAsInt = 'A';
std::cout << valueAsInt << "\n";
A
65
Take the value of the character literal '0'. This corresponds to the ASCII value 48. '1' is 49, etc.
If you subtract 48 from 49, you get 1. But that's not what you're looking for.
The ASCII value 1 corresponds to a non-printable character, called "start of heading". It was once used on old printers as a sort of markup. It would not print, but it would modify how further characters are printed.
When you subtract one numeric character from another, you get a delta, not a printable character. To turn this delta back into a printable character, you have to add it to a base character:
char value = '5' - '3';
value += '0';
std::cout << "5 - 3 = " << value << "\n";
5 - 3 = 2
So, your code such as message[0] - myTempString[0] must be changed to message[0] - myTempString[0] + '0' in order to work the way you intend it to.