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
Can someone help me to write a few c++ lines of code to convert an input string letters as follow:
Lowercase letters to Uppercase letters.
Uppercase letters to lowercase letters.
libraries functions are not allowed.
if statement, comparisons, | operation and & not allowed.
Thanks.
You can write an translation array (= map).
a -> A
A -> a
b -> B
B -> b
...
z -> Z
Z .. z
For ASCII you can implement it as a char[] with 128 entries and simply use the character of you source as index to read the resulting character.
char translate[128];
translate['A']='a';
...
Possible Implementation:
// The following init-String is quite long (128 characters)!
char* translate=" abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
int i=0;
while(0!=s[i])
s[i] = translate[s[i++]];
If your input is ASCII, you can simply invert bit 5 which means xor the value 32 to each character. That will convert lowercase to upper case and vici versa.
Only problem is it only works for a-zA-Z and nothing else.
You can use a combination of std::transform and the functions toupper and tolower.
EDIT: sorry missed your last two points. You will have to perform a cycle like for and you may use the ternary operator ? to avoid if statements. A possible solution for to upcase is:
for (unsigned i = 0; i < s.size(); ++i) {
s[i] = (s[i] >= 'a' && s[i] <= 'z') ? s[i] - 'a' + 'A' : s[i];
}
Something like this would work, but only if you have alphabets
char c = 'a';
int e = c;
int d = e < 90 ? e + 32 : e - 32;
My solution: was looking for others.
string s;
cin>>s;
int a[3] = {'A', 'a', 'a'};
int A[3] = {'a', 'A', 'A'};
for (int i=0; i<s.size(); ++i)
s[i] = s[i] - a[(s[i]-'A')/26] + A[(s[i]-'A')/26];
cout << s << endl;
Thanks for trying.
Related
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
This is the program for converting the ascii sentence to character sentence. But i dont understand the num = num * 10 + (str[i] - '0'); why it us used and why it's needed?
#include <bits/stdc++.h>
using namespace std;
void asciiToSentence(string str, int len)
{
int num = 0;
for (int i = 0; i < len; i++) {
num = num * 10 + (str[i] - '0');
if (num >= 32 && num <= 122) {
char ch = (char)num;
cout << ch;
num = 0;
}
}
}
int main()
{
string str = "973265";
int len = str.length();
asciiToSentence(str, len);
return 0;
}
Firstly, bits/* are not standard headers, you shouldn't be using them otherwise your code may not compile with compilers like MSVC. Refer this.
Now let's come to your query : str[i] - '0' is simply a way to convert char to respective int, i.e. '0' to 0. You can find more discussion on this thread.
What does your code do?
It just keeps on extracting chars from your string (in loop), converting it to int and adding to num after multiplying it by 10. This is basically converting a part of string, say, "97" to an integer 97.
When num comes in range from 32 (' ') to 122 ('Z') (both inclusive), it cast them to char and prints it.
Explanation of Sample Output:
Your code prints a A to console. You will get this result if you can figure out the substrings. Here consider these three - "97" "32" "65". Then "97" will be converted to 97 (as int), then will be cast to char and end up being 'a' ('a' has ASCII value of 97). Similarly "32", will be a space ' ', and "65" will be 'A'.
These substrings didn't come here by magic. Let me explain one for you :
You have str = "973265", num = 0, then the loop begins :
i = 0 -> str[i] = '9' -> str[i] - '0' = 9 -> num = 0*10 + 9 = 9 -> is num in range [32, 122]? false -> go to next iteration.
i = 1 -> str[i] = '7' -> str[i] - '7' = 7 -> num = 9*10 + 7 = 97 -> is num in range [32, 122]? true -> ch = (char)num = (char)97 = 'A' -> print ch, i.e. 'A' -> num = 0 -> go to next iteration.
Pro Tip: Use your debugger, set breakpoints, watch variables and step through your code for better understanding.
Note that: When I wrote ____ - I meant ____ like this ____.
"convert" -- conversion -- '0' <-> 0 or "12" <-> 12
"cast" -- casting -- '0' <-> 48 (assuming your compiler is using ASCII).
In http://www.asciitable.com/, you can see that 0 has ascii value of 48, 1 is 49, 2 is 50 and so on.
So str[i] - '0' will give you 0 if str[i] == '0', 1 if str[i] == '1' and so on. This is a simple trick to convert numeric char into its mathematical value.
Let's call str[i] - '0' as x, so the line you don't understand becomes num = num * 10 + x. What this does is, take the original num (say it was 32), add a 0 behind it (so it becomes 320), then add x (if x is 7, num becomes 327).
So overall, this code is basically a function that converts a number string into integer type.
Well currently I am re creating my own version of enigma as a little project but if you understand how the enigma machine works it has rotors which connect a character to a completely different character for example A might be connected to F or U may be connected to C and this is done three times. Currently I am getting the char for the rotor by using this function:
char getRotorOne(char i) {
if(i == 'a') {
return 'g';
}if(i == 'b') {
return 'A';
}if(i == 'c') {
return 'o';
}
The main problem with this is it takes a long time to write and it seems inefficient and I think there must be a better way. The other problem with this is on the original enigma machine there were only the 26 letters of the alphabet on this there are the 94 tapeable characters of ascii (32-126) is there any other simpler way that this can be done? If you think this question is unclear or you don't understand please tell me instead of just flagging my post, then you can help me improve my question.
Use tables! Conveniently, C string literals are arrays of characters. So you can do this:
// abc
const char* lower_mapping = "gAo";
// ABC
const char* upper_mapping = "xyz";
char getRotorOne(char i) {
if (i >= 'a' && i <= 'z') return lower_mapping[i - 'a'];
if (i >= 'A' && i <= 'Z') return upper_mapping[i - 'A'];
assert(false && "Unknown character cannot be mapped!");
}
Since chars are really just small integers, and ASCII guarantees contiguous ranges for a-z and A-Z (and 0-9) you can subtract from a given character the first one in its range (so, 'a' or 'A') to get an index into that range. That index can then be used to look up the corresponding character via a table, which in this case is just a simple hardcoded string literal.
This is an improvement on Cameron's answer. You should use a simple char array for each rotor, but as you said you want to process ASCII characters in the range 32-126, you should build each mapping as an array of 95 characters:
char rotor1[95] ="aXc;-0..."; // the 95 non control ascii characters in arbitrary order
Then you write your rotor function that way:
char getRotorOne(char i) {
if ((i < 32) || (i > 126)) return i; // do not change non processed characters
return rotor1[i - 32]; // i - 32 is in range 0 - 94: rotor1[i - 32] is defined
}
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 8 years ago.
Improve this question
So, in this program we have to
A. Count the number of each letter of the alphabet found in a character array and store these counts in an integer array
I understand that part but then it says we have to use the ASCII values which confuses me.
This is the file for reference:
" A frog walks into a bank and asks the teller, Miss Pattywack
for a loan. Miss Pattywack tells the frog,
"you must have collateral for the loan".
The frog pulls out of his pouch his porcelain people collection
and offers them as collateral.
Miss Pattywack looks at the figurines and tells the frog that
the collection is not acceptable.
The bank manager overhears the conversation and yells to the
teller - "It's a nick nack Pattywack, give the frog a loan!"
Use a for loop to examine each character in the character array
i. Use toupper to case the letter, so you are only dealing with capital letters
ii. If the character is a letter of the alphabet, increment the integer array in the position of the ASCII value of the character minus 65
1) 65 is the ASCII value of letter, 'A'
(1) If the character is A, 65-65 = 0 the position you want to increment for the character A
(2) If the character is C, 67-65 = 2 the position you want to increment for the character C
I have this so far:
void CountAlphabetCharacters(char chArray[MAX_CHARACTERS], int lengthOfArray)
{
int index;
for(index = 0; index <= lengthOfArray; index++)
{
chArray[index] = toupper(chArray[index]);
static_cast<int>(index);
}
}
That's all I have because that's all I understand. I mean, I understand how you get the ASCII value but I am so lost on how to actually make the for loop for this. Like I'm assuming you look at the characters from the file but I don't understand how you get that value you and keep going. I don't know if I make sense but I'm hoping I do and someone can help!! Thanks in advance.
Things you need:
An array to hold the characters that you read. I think chArray is that array.
An array to hold the count of the letters of the alphabet. I don't see that array.
Update the code in CountAlphabetCharacters to go through the characters in chArray and update the count of letters in chArray.
Before calling CountAlphabetCharacters, create the array for holding the count of characters.
int charCountArray[26] = {0};
Change the function CountAlphabetCharacters to accept it as an argument.
void CountAlphabetCharacters(char chArray[MAX_CHARACTERS],
int charCountArray[],
int lengthOfArray)
Use it as an argument in the call to CountAlphabetCharacters.
Update the implementation of CountAlphabetCharacters.
void CountAlphabetCharacters(char chArray[MAX_CHARACTERS],
int charCountArray[],
int lengthOfArray)
{
int index;
int ch;
for(index = 0; index <= lengthOfArray; index++)
{
// The character at the index.
ch = chArray[index];
// Check whether it is an alphabetical character.
if ( isalpha(ch) )
{
// If so, make it the uppercase letter.
ch = toupper(ch);
// Increment the charCountArray for the letter.
charCountArray[ch-'A']++;
}
}
}
void CountAlphabetCharacters(char chArray[MAX_CHARACTERS], int lengthOfArray)
{
int index;
int counter[26]={0}; // holds occurrence of each character
for(index = 0; index < lengthOfArray; index++)
{
if(isalpha(chArray[index]){
int val = (int)toupper(chArray[index]);
counter[val-65]++; //increment occurrence count for this character
}
}
for(char c ='A',index = 0; index <26; index++,c++)
{
printf("%c : %d", c, counter[index]); //print character and corresponding occurrence
}
}
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 8 years ago.
Improve this question
I need to separate users input into units and store them in an array.
e.g if user enters 6547. Array will store {6,5,4,7} Using C++ on Linux
I would appreciate if you can help me with pseudocode or explain an algorithm.
I'm a beginner so please restrain from advising advanced function (and explain its use if you do) as we have studied basics so far
N.B| If such question has already been answered and I skipped it in search, please do point me to it.
The math for isolating right most digit:
digit = digit % 10;
The math for shifting a number right by one digit:
new_number = old_number / 10;
Every letter and number can be represented as a text character. For example, '5' is a character representing the single decimal digit 5.
The math for converting a textual digit (character) to numeric:
digit = char_digit - '0';
Example:
digit = '9' - '0';
The math for converting a numeric digit to a textual digit (character):
char_digit = digit + '0';
Example:
char_digit = 5 + '0';
Your problem basically breaks into few parts, which you need to figure out:
how to read one character from input
how to convert one character to the digit it represents
how to store it in the array
Please, try to explain if you have problem with some particular point from the list above or there is a problem somewhere else.
Suppose Variable input_string holds the number entered by the user & you want to store it in an array named 'a'...Here's a C snippet.. you can easily convert it into C++ code..
I would recommend taking the input as string rather than int so that you can directly insert the digits extracted from the end...(else you can start storing the integer from beginning and then reverse the array)
scanf("%s",&input_string)
size = strlen(input_string)-1
input = atoi(input_string)
while (input/10>0)
{
i=input%10;
input=input/10;
a[size]=i;
size--;
}
Hope that helps!
Here's a C++11 solution:
std::string input;
std::cin >> input;
int num = std::stoi(input);
std::vector<int> v_int;
for (unsigned int i = 0; i < input.size(); i++)
{
v_int.push_back(num % 10);
num /= 10;
}
// To get the numbers in the original order
std::sort(v_int.rbegin(), v_int.rend());
for (unsigned int i = 0; i < v_int.size(); i++) {
std::cout << v_int[i] << std::endl;
}
If you want it in a c-style array, do this:
int* dynamic_array = new int[v_int.size()];
std::copy(v_int.begin(), v_int.end(), dynamic_array);
delete dynamic_array;
To start off, I'm four weeks into a C++ course and I don't even know loops yet, so please speak baby talk?
Okay, so I'm supposed to read a twelve character string (plus NULL makes thirteen) from a file, and then shift the letters backwards three, and then print my results to screen and file. I'm okay with everything except the shifting letters. I don't want to write miles of code to take each character individually, subtract three, and re-assemble the string, but I'm not sure how to work with the whole string at once. Can someone recommend a really simple method of doing this?
If you are dealing with simple letters (A to Z or a to z), then you can assume that the internals codes are linear.
Letters are coded as numbers, between 0 and 127. A is coded as 65, B as 66, C as 67, Z as 90.
In order to shift letters, you just have to change the internal letter code as if it were a number, so basically just substracting 3 from the character. Beware of edge cases though, because substracting 3 to 'A' will give you '>' (code 62) and not 'X' (code 88). You can deal with them using "if" statements or the modulo operator ("%").
Here is an ASCII characters table to help you
Once you've loaded your string in, you can use the modulous operator to rotate while keeping within the confines of A-Z space.
I'd keep track of whether the letter was a capital to start with:
bool isCaps = ( letter >= 'A' ) && ( letter <= 'Z' );
if( isCaps )
letter -= 'A'-'a';
and then just do the cipher shift like this:
int shift = -3;
letter -= 'a'; // to make it a number from 0-25
letter = ( letter + shift + 26 ) % 26;
// add 26 in case the shift is negative
letter += 'a'; // back to ascii code
finally finish off with
if( isCaps )
letter += 'A'-'a';
so, putting all this together we get:
char *mystring; // ciphertext
int shift = -3; // ciphershift
for( char *letter = mystring; letter; ++letter )
{
bool isCaps = ( *letter >= 'A' ) && ( *letter <= 'Z' );
if( isCaps )
*letter -= 'A'-'a';
letter -= 'a';
letter = ( letter + shift + 26 ) % 26;
letter += 'a';
if( isCaps )
letter += 'A'-'a';
}
You're going to have to learn loops. They will allow you to repeat some code over the characters of a string, which is exactly what you need here. You'll keep an integer variable that will be your index into the string, and inside the loop do your letter-shifting on the character at that index and increment the index variable by one until you reach NULL.
Edit: If you're not expected to know about loops yet in your course, maybe they want you to do this:
string[0] -= 3; // this is short for "string[0] = string[0] - 3;"
string[1] -= 3;
string[2] -= 3;
...
It will only result in 12 lines of code rather than miles. You don't have to "reassemble" the string this way, you can just edit each character in-place. Then I bet after making you do that, they'll show you the fast way of doing it using loops.
Iterate over the characters with a for loop. And do what you want with the char*. Then put the new char back.
for(int i=0; i<12; i++){
string[i] = string[i] - 3;
}
Where string is your character array (string). There is a bit more involved if you want to make it periodic (I.E. have A wrap round to Z, but the above code should help you get started)
I'm a little unclear what you mean by "shift the letters backwards 3"?
Does that mean D ==> A?
If so, here's a simple loop.
(I didn't do reading from the file, or writing to the file... Thats your part)
#include <string.h>
int main(void)
{
char input[13] = "ABCDEFGHIJKL";
int i;
int len = strlen(input);
for(i=0; i<len; ++i)
{
input[i] = input[i]-3;
}
printf("%s", input); // OUTPUT is: ">?#ABCDEFGHI"
}