Last consonant of a text [closed] - c++

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 7 years ago.
Improve this question
After a user enters a text (with spaces), how do I delete only the last consonant of that certain text?
I have no idea how to do that, whatever I did by now deleted all the consonants.

Have you tried something or you have no idea how to do it?
I'll assume you didn't do anything yet.
First of all, you have to find the last consonant. How do you do that. Well, you start from the end and check the letter until you find a consonant.
Now, when you find the last consonant, you memorize the position of the consonant and then move every letter that's to the right of the consonant to the left.
And lastly, change the last character in the string to the '\0'.
Here is the code:
#include <iostream>
#include <string>
#include <cctype>
bool isConsonant(char);
int main (int argc, char *argv[]) {
char s[80];
// Input the text
std::cout << "Enter the text: ";
std::cin.getline(s,80,'\n');
// Creating string object
std::string text(s);
int length = text.length();
// Searching for the last consonant
int i = length - 1;
while ((!isConsonant(text.at(i)) && (i)))
i--;
// Moving every letter after the last consonant one place to the left
for (int j = i; j < length - 1; j++)
text.at(j) = text.at(j+1);
text.at(length-1) = '\0';
// Printing the text to the standard output
std::cout << text;
return 0;
}
bool isConsonant(char c) {
if (isalpha(c)) {
char temp = c;
if (isupper(c))
temp = tolower(c);
return !((temp == 'a') || (temp == 'e') || (temp == 'i') || (temp == 'o') || (temp == 'u'));
}
return false;
}
Edit: Of course there are other ways to do this, and you should try to think of them. This is a first thing that came to my mind.

Related

There is an error in this program. Please can anyone identify it? Thanks [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 5 years ago.
Improve this question
Hi all there seems to be an error in this program in the sense it is showing wrong output. Rather than showing number of consonants and vowels it is printing the length of the string.
#include<iostream>
using namespace std; // program to display the vowels and consonants of a string
int countvowels(char a[])
{
int count =0;
for(int i =0; a[i]!='\0';i++)
{
if((a[i]>=65 && a[i]<=90) || (a[i]>=97 && a[i]<=122)) // ignores digits,special characters
{
if((a[i]=65) || (a[i]=69) || (a[i]=73) || (a[i]=79) || (a[i]=85) || (a[i]=97) || (a[i]=101) || (a[i]=105) || (a[i]=111) || (a[i]=117) ) //ignores consonants
{
count++; //counts filtered out vowels
}
}
}
return count; // returns number of vowels which will be captured by x of main function
}
int countconsonants(char a[])
{
int count =0;
for(int i =0; a[i]!='\0';i++)
{
if((a[i]>=65 && a[i]<=90) || (a[i]>=97 && a[i]<=122)) // ignores digits,special characters
{
if((a[i]!=65) || (a[i]!=69) || (a[i]!=73) || (a[i]!=79) || (a[i]!=85) || (a[i]!=97) || (a[i]!=101) || (a[i]!=105) || (a[i]!=111) ||(a[i]!=117) ) //ignores vowels
{
count++; //counts filtered out consonants
}
}
}
return count; // returns number of consonants which will be captured by y of
main function
}
int main()
{
char a[100];
cout<<"Enter the string"<<endl;cin.get(a,100);
int x = countvowels(a);
int y = countconsonants(a);
cout<<"Number of vowels is"<<x<<endl; //nothing much to say about this part of the program. x just displays it and y does the same
cout<<"Number of consonants is"<<y<<endl;
return 0;
}
Here are the ASCII values of vowels.
A , a = 65,97
E,e = 69, 101
I,i = 73, 105
O,o = 79,111
U,u = 85,117
You have two problems with your code:
In checking for equality. To check if two value are equal you should use double equals== instead of a single equals. A single equal sign will mean assignment not equality check
In logical condition in count_consonants. a != 1 || a != 2 will always evaluate to true

Finding words in sentences [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a programming assignment I cannot finish. This one part is killing me.
Accept some text from the user. Accept the string that needs to be searched. Your program is supposed to print the number of occurrences of the string found within the text, and the position at which the pattern was found. Look at the following sample output:
Sample Output:
Enter text: “Call me Ishmael. Some years ago - never mind how long precisely - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen, and regulating the circulation”
String to search – “Some years ago”
Number of occurrences – 1
Position Found – 18
This is my function:
void getText()
{
string itext, word;
int position;
bool done = false;
cout << "Enter some text" << endl;
cin >> itext;
cout << "Enter the word or phrase to wish to find" << endl;
cin >> word;
char text[itext.length()];
char search[word.length()];
for(int i = 0; i < itext.length(); i++)
{
for(int j = 0; j < word.length(); j++)
{
if(text[i] == search[j])
{
position = i;
cout << position;
}
}
}
}
This might get you started: (pseudo code from the Knuth-Morris-Pratt algorithm)
algorithm kmp_search:
input:
an array of characters, S (the text to be searched)
an array of characters, W (the word sought)
output:
an integer (the zero-based position in S at which W is found)
define variables:
an integer, m ← 0 (the beginning of the current match in S)
an integer, i ← 0 (the position of the current character in W)
an array of integers, T (the table, computed elsewhere)
while m + i < length(S) do
if W[i] = S[m + i] then
if i = length(W) - 1 then
return m
let i ← i + 1
else
if T[i] > -1 then
let m ← m + i - T[i], i ← T[i]
else
let i ← 0, m ← m + 1
(if we reach here, we have searched all of S unsuccessfully)
return the length of S
http://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
EDIT:Simpler and using c++ std library :
#include <string>
#include <vector>
int main ()
{
std::string str ("There are two needles in this haystack with needles.");
std::string str2 ("needle");
// different member versions of find in the same order as above:
std::size_t found = 0;
int matches = 0;
std::vector<size_t> positions;
while( found = str.find(str2) != std::string::npos) {
matches++;
positions.push_back(found);
}
}
You can make your live much easier if you will use std::string in this task instead of char[]. All you have to do is to load your text into a std::string and then use its find method as described here:
http://www.cplusplus.com/reference/string/string/find/
By the way, I am not sure that these lines can work as you can create not dynamic array only with a constant expression length
char text[itext.length()];
char search[word.length()];

Comparing two strings to see if they are rotation [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 8 years ago.
Improve this question
Rotation means one string is created from moving the other string one or more bits to the right. For example abc and cab are rotation, abcd and bacd are not rotation.
I wrote the code below however it's failed to pass the last one test case (don't know what it is). Could anyone give me some hints about where goes wrong or is there any more efficient algorithm:
int isLetterInWord(char c, char* word)//find first letter in the word which is equal to c
{
int len = strlen(word);
for(int i=0; i<len; ++i)
{
if(c==word[i])
return i;
}
return -1;
}
int isRotation(char* word1, char* word2)
//check if word1 and word2 are rotation. if so return 1 otherwise -1
{
if(word1 == NULL && word2 == NULL)
return 1;
int len1 = strlen(word1);
int len2 = strlen(word2);
if(len1!= len2)
return -1;
for(int i=0; i<len1; ++i)
{
int pos = isLetterInWord(word1[i], word2);
if(pos == -1)
return -1;
else
{
int p1 = i, p2 = pos;
int cnt=0;
while(cnt<len1)
{
if(word1[p1++]!=word2[p2++])
break;
if(p1==len1)p1=0;
if(p2==len2)p2=0;
cnt++
}
if(cnt==len1)
return 1;
}
}
return -1;
}
Another algorithm of solving this question is as follow:
Lets say first string is str1 and need to check whether str2 is rotation of str1.
The algorithm is as follow:
concatanate str1 to str1. Lets call it str3.
Now check whether str2 is a sub-string of str3.
If str2 is sub-string of str3 then it is a rotation of str1 otherwise not.
Please find the function to check rotation of a string:
int Rotations(char *str1, char *str2)
{
int size1 = strlen(str1);
int size2 = strlen(str2);
char *temp;
void *ptr;
if (size1 != size2)
return 0;
temp = (char *)malloc(sizeof(char)*(size1*2 + 1));
temp[0] = '\0';
strcat(temp, str1);
strcat(temp, str1);
ptr = strstr(temp, str2);
free(temp);
if (ptr != NULL)
return 1;
else
return 0;
}
if(word1==NULL&&word2==NULL)
This should be
if(word1==NULL||word2==NULL)
Not gone through your logic.
Overview: Find first char matching char in string, Then perform xor on string, Till end of minimum length string, This way you can find whether string are rotation string of each other
Pre-Condition: Length of both strings are equal, As already stated above answers
Step 1: Find first matching char in both string notice pos(position) of char in the first string.
Step 2: Now perform xor on first string from pos to the end of first string, With substring with same length from the second string.
Step 3: If result xor is 0 means First part matches of the string matched, And proceed to match remaining part(substring), Which is first char in the first string to char at pos-1, And substring from second string from pos+1 to end of string, Then perform same xor on them,
Step 4: If that matches then exit with sucess, And if does not match then find next matching char in first string, and repeat from step 2, until reaches end of the first string

Stack corruption in message-encoding program [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I'm trying to write a C++ program that creates a list of letters that will
be used to encode a message according to the following rules:
Input a word
Remove all repeating letters to form the modified word
Place the modified word at the beginning of the array
Fill the remainder of the list with any letters of the alphabet that were not used in the word working from A to Z. (Your list should have all 26 letters of the alphabet)
For example, if the user enters HELLO, the modified word would become HELO, and the list would become HELOABCDFGIJKMNPQRSTUVXYZ. The list must be stored in an array of CHARacters.
This is the code I've written:
#include <iostream>
using namespace std;
int main()
{
char a;
int b = 0;
char word[4] = "\0";
char alphabet[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char code[27];
cout << "Please enter a word:" << endl;
cin >> word;
for (int i = 0; i<3; i++)
{
if (word[i] == word[i - 1])
{
a = word[i];
word[i] = word[i + 1];
}
code[i] = word[i];
b++;
}
for (int o = 0; o<27; o++)
{
if (alphabet[o] == word[1] || alphabet[o] == word[2] || alphabet[o] == word[3] || alphabet[o] == word[0])
{
o++;
}
code[b] = alphabet[o];
b++;
}
cout << code;
return 0;
}
Unfortunately, I'm getting this error:
Run-Time Check Failure #2
Stack around the variable word was corrupted.
Secondly, my code works for 4 characters. How can I make it work for any word?
this is a simple way to do this assignment.
note that input word lenght should be smaller than 100
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char word[100]; // input word lenght should be smaller than 100
char used[26];
memset(used, 0, 26);
scanf("%s", word);
for (int i=0; i<strlen(word); i++)
{
// convert to uppercase
if (word[i]>='a' && word[i]<='z')
word[i] -= 'a'-'A';
// skip non-alphabetic characters
if (word[i]<'A' || word[i]>'Z')
continue;
// print this char only if it's not been printed before
if (!used[word[i]-'A'])
printf("%c", word[i]);
// set to 1 so that we don't print it again
used[word[i]-'A'] = 1;
}
// print all unused characters
for (int i=0; i<26; i++)
if (!used[i])
printf("%c", i+'A');
printf("\n");
return 0;
}

Cant find same letters in word [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
can somebody give some explanation how to find same letters in word?
There is the code, but its returning whole word as same letters
int Sting::SameLetters(string word, string sk) {
string find;
find = word;
for (int i = 0; i < word.length(); i++)
{
if ((find.find(tolower(word[i])) == string::npos) &&
(sk.find(word[i]) == string::npos))
{
sk += word[i];
}
}
return sk.length();
}
So i tried to remake code and now its counting letters, but not all
int letters(string word, string sk)
{
sk = word[0];
int lenght = 0;
for ( int i =0; i <= word.length(); i++)
{
if(tolower(sk[0]) == tolower(word[i]))
{
lenght++;
}
sk = word[i];
}
return lenght;
}
My used words for test
ssabba ccea
Results
ssabba(3) ccea(2)
I have to get ssabba(6)
Think about the logic of that if statement for a while.
You initialize find to be the same as word, so when you do
find.find(tolower(word[i])) == string::npos
it will indeed find the character, and the expression will be false. And because that expression is false, due to the short-circuit nature of the logical and operator && the second check will not happen. This means that the sk += word[i] statement will never happen, and you will return the length of the unmodified sk.
I'm not exactly sure what you try to do, but that condition most definitely is not doing what you think it does.
Please have a look at the std::string::find reference. This function will search for the first occurrence in the whole string. You're iterating about all characters, so probably you just want to compare character by character to estimate the count of occurrences from a specific character? Assuming your parameter sk is a std::string with a .length() from exactly 1, you could do it like this:
size_t sameLetters(const std::string& word, const std::string& sk) {
size_t length = 0;
for (size_t i = 0; i < word.length(); i++){
if(tolower(word[i]) == tolower(sk[0]))
length++;
}
return length;
}
That would always return the number of occurrences. i.e.
sameLetters("Aaabc", "a"); /* returns 3 */
sameLetters("hello", "l"); /* returns 2 */
sameLetters("some string", "Z"); /* returns 0 */
If you tried to accomplish something different please elaborate.