How to add dot character to a character in string? - c++

I want to add '.' character besides another character in a string but I don't know how to do it ? is it possible?
#include <iostream>
#include <string.h>
using namespace std;
int main(int argc, char *argv[]) {
string input;
char dot='.';
cin>>input;
for(int i=0;i<input.length();i++)
{
if( input[i]>=65 && input[i]<=90)
{
input[i]=input[i]+32;
}
if( (input[i]=='a') || (input[i]=='e') || (input[i]=='i') || (input[i]=='o') || input[i]=='y' || input[i]=='u' )
{
input.erase(i,i+1);
}
input[i]+=dot;
}
cout<<input<<endl;
return 0;
}

From the cpluplus.com reference ( http://www.cplusplus.com/reference/string/string/insert/ )
// inserting into a string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str="to be question";
string str2="the ";
string str3="or not to be";
string::iterator it;
// used in the same order as described above:
str.insert(6,str2); // to be (the )question
str.insert(6,str3,3,4); // to be (not )the question
str.insert(10,"that is cool",8); // to be not (that is )the question
str.insert(10,"to be "); // to be not (to be )that is the question
str.insert(15,1,':'); // to be not to be(:) that is the question
it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question
str.insert (str.end(),3,'.'); // to be, not to be: that is the question(...)
str.insert (it+2,str3.begin(),str3.begin()+3); // (or )
cout << str << endl;
return 0;
}
Also, check these links:
http://www.cplusplus.com/reference/string/string/
http://www.cplusplus.com/reference/string/string/append/
http://www.cplusplus.com/reference/string/string/push_back/

Before you try writing the code, you should write a detailed
specification of what it is supposed to do. With your code, I
can only guess: convert to lower case (naïvely, pretending that
you'll only encounter the 26 unaccented letters in ASCII), then
delete all vowels (again, very naïvely, since determining
whether something is a vowel or not is non-trivial, even in
English—consider the y in yet and day), and finally
inserting a dot after each character. The most obvious way of
doing that would be something like:
std::string results;
for ( std::string::const_iterator current = input.begin(),
end = input.end();
current != end;
++ current ) {
static std::string const vowels( "aeiouAEIOU" );
if ( std::find( vowels.begin(), vowels.end(), *current )
!= vowels.end() ) {
results.push_back(
tolower( static_cast<unsigned char>( *current ) ) );
}
results.push_back( '.' );
}
But again, I'm just guessing as to what you are trying to do.
Another alternative would be to use std::transform on the
initial string to make it all lower case. If you're doing this
sort of thing regularly, you'll have a ToLower functional
object; otherwise, it's probably too much of a bother to write
one just to be able to use std::transform once.

I’m assuming you want this input:
Hello world!
To give you this output:
h.ll. w.rld!
Rather than trying to modify the string in place, you can simply produce a new string as you go:
#include <cctype>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
string input;
getline(cin, input);
string output;
const string vowels = "aeiouy";
for (int i = 0; i < input.size(); ++i) {
const char c = tolower(input[i]);
if (vowels.find(c) != string::npos) {
output += '.';
} else {
output += c;
}
}
cout << output << '\n';
return 0;
}
Notes:
<cctype> is for toupper().
<string.h> is deprecated; use <string>.
Read whole lines with getline(); istream::operator>>() reads words.
Use tolower(), toupper(), &c. for character transformations. c + 32 doesn’t describe your intent.
When you need comparisons, c >= 'A' && c <= 'Z' will work; you don't need to use ASCII codes.
Use const for things that will not change.

I'm not sure how this old question got bumped back onto the current list, but after reviewing the answers, it looks like all will miss the mark if the input is more than a single word. From your comments, it appears you want to remove all vowels and place a '.' before the character immediately prior to where the removal occurred. Thus your example "tour" becomes ".t.r".
Drawing from the other answers, and shamelessly removing 'y' as from the list of vowels, you can do something similar to:
#include <iostream>
#include <string>
int main()
{
std::string input;
if (!getline (std::cin, input)) {
return 1;
}
size_t i = 0;
for (; input[i]; i++)
{
switch (input[i])
{
case 'A': /* case fall-through intentional */
case 'E':
case 'I':
case 'O':
case 'U':
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
{
size_t pos = input.find_first_not_of("AEIOUaeiou", i+1);
if (pos == std::string::npos) {
pos = input.length();
}
input.erase(i, pos-i);
if (pos - i > 1) {
input.insert(i, 1, '.');
}
input.insert(i-1, 1, '.');
break;
}
}
}
std::cout << input << '\n';
}
Example Use/Output
Your example:
$ ./bin/vowels-rm-mark
tour
.t.r
A longer example:
$ ./bin/vowels-rm-mark
My dog has fleas and my cat has none.
My .dg .hs f.l.s. nd my .ct .hs .n.n.

Based on your comments, it sounds like you want something like this:
#include <iostream>
#include <string>
#include <algorithm>
int main(int argc, char *argv[])
{
std::string input;
std::cin >> input;
std::transform (input.begin(), input.end(), input.begin(), tolower);
size_t i = 0;
while (i < input.length())
{
switch (input[i])
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'y':
case 'u':
{
size_t pos = input.find_first_not_of("aeioyu", i+1);
if (pos == std::string::npos)
pos = input.length();
input.erase(i, pos-i);
break;
}
default:
{
input.insert(i, 1, '.'); // or: input.insert(i, ".");
i += 2;
break;
}
}
}
std::cout << input << std::endl;
return 0;
}

Related

How to pass a cstring as a function parameter/argument

I have a small program that prints out the capital form of each letter of a word, but I get the error signed/unsigned mismatch when I compile it because I'm passing a cstring as a normal string in this program. How do I pass it correctly so that I can still use text.length()? Here is the error that I get "Tester.cpp(22,23): warning C4018: '<': signed/unsigned mismatch". It's at for (int i = 0; i < text.length(); i++)
#include <iostream>
using namespace std;
string capitalizeFirstLetter(string text);
int main() {
char sentence[100];
for ( ; ; )
{
cin.getline(sentence, 100);
if (sentence != "0")
capitalizeFirstLetter(sentence);
}
return 0;
}
string capitalizeFirstLetter(string text) {
for (int i = 0; i < text.length(); i++)
{
if (i == 0)
{
text[i] = toupper(text[i]);
}
if (text[i] == ' ')
{
++i;
text[i] = toupper(text[i]);
}
}
cout << text;
return text;
}
The simplest way to handle passing sentence as a string is to enclose it in a braced set, to provide direct initialization to the parameter std::string text eg..
for ( ; ; )
{
std::cin.getline(sentence, 100);
if (*sentence)
capitalizeFirstLetter({sentence});
}
This allows the character string sentence to be used as the Direct initialization to initialize std::string text in your capitalizeFirstLetter() function:
std::string capitalizeFirstLetter (std::string text) {
for (size_t i = 0; i < text.length(); i++)
{
if (i == 0)
{
text[i] = toupper(text[i]);
}
if (text[i] == ' ')
{
++i;
text[i] = toupper(text[i]);
}
}
std::cout << text;
return text;
}
Your complete code, after reading Why is “using namespace std;” considered bad practice?, would then be:
#include <iostream>
std::string capitalizeFirstLetter (std::string text) {
for (size_t i = 0; i < text.length(); i++)
{
if (i == 0)
{
text[i] = toupper(text[i]);
}
if (text[i] == ' ')
{
++i;
text[i] = toupper(text[i]);
}
}
std::cout << text;
return text;
}
int main (void) {
char sentence[100];
for ( ; ; )
{
std::cin.getline(sentence, 100);
if (*sentence)
capitalizeFirstLetter({sentence});
}
return 0;
}
(note: dereferencing sentence provides the first character which is then confirmed as something other than the nul-terminating character (ASCII 0))
A Better CapitalizeFirstLetter()
A slightly easier way to approach capitalization is to include <cctype> and an int to hold the last character read. Then the logic simply loops over each character and if the first character is an alpha-character, then capitalize it, otherwise only capitalize the letter when the current character is an alpha-character and the last character was whitespace, e.g.
std::string capitalizeFirstLetter (std::string text)
{
int last = 0
for (auto& c : text)
{
if (isalpha(c))
{
if (!i || isspace (last))
c = toupper(c);
}
last = c;
}
std::cout << text;
return text;
}
(note: the use of a range-based for loop above)
Either way works.
The error is not generating because of you passing a cstring as a normal string to the function but it is due to the fact that you are trying to compare c style string using != operator in the statement
if (sentence != "0")
capitalizeFirstLetter(sentence);
try using strcmp() for that
Several things bugging me here.
First off, don't use using namespace std, it's "ok" in this case, but don't get used to it, it can cause quite some trouble.
See Why is “using namespace std;” considered bad practice?
Next thing is, just use std::string instead of cstrings here, it's easier to write and to read and doesn't produce any measurable performance loss or something. And it's harder to produce bugs this way.
So just use
std::string sentence;
and
getline(std::cin, sentence);
And why do you handle the output inside the function that transforms your string? Just let the main print the transformed string.
So your main could look like this:
int main() {
std::string sentence;
while(true)
{
getline(std::cin, sentence);
auto capitalized = capitalizeFirstLetter(sentence);
std::cout << capitalized;
}
return 0;
}
PS: the 'error' you get is a warning, because you compare int i with text.length() which is of type size_t aka unsigned int or unsigned long int.
Problems with your code :
if (sentence != "0") : illegal comparison. If you want to break on getting 0 as input then try using strcmp (include <cstring>) as if (strcmp(sentence, "0"). (Note that strcmp returns 0 when two strings are equal.) Or simply do if (!(sentence[0] == '0' and sentence[1] == 0)). Moreover this condition should be accompanied with else break; to prevent the for loop from running forever.
for (int i = 0; i < text.length(); i++) : generates warning because of comparison between signed and unsigned types. Change data-type of i to string::size_type to prevent the warning.
<string> (for std::string) and <cctype> (for std::toupper) were not included.
Thanks to #john for pointing this out. Your code has undefined behaviour if last character of a string is a space. Add a check if i is still less than text.length() or not before using text[i].
Another case of error is when an space is there after 0. Move getline to condition of for to fix this. Now there will be no need to input a 0 to terminate program. Moreover, I recommend using while loop for this instead of for.
You may also need to print a newline to separate sentences. Moreover, I would prefer printing the modified sentence in the main() function using the returned string from capitalizeFirstLetter.
It doesn't matter much in short (beginner-level) codes, but avoid acquiring the habit of putting using namespace std; on the top of every code you write. Refer this.
Fixed code :
#include <cctype>
#include <cstring>
#include <iostream>
#include <string>
using namespace std;
string capitalizeFirstLetter(string text);
int main() {
char sentence[100];
while (cin.getline(sentence, 100))
cout << capitalizeFirstLetter(sentence) << '\n';
}
string capitalizeFirstLetter(string text) {
for (string::size_type i = 0; i < text.length(); i++) {
if (i == 0)
text[i] = toupper(text[i]);
if (text[i] == ' ')
if (++i < text.length())
text[i] = toupper(text[i]);
}
return text;
}
Sample Run :
Input :
hello world
foo bar
Output :
Hello World
Foo Bar
My Version (Requires C++20) :
#include <cctype>
#include <iostream>
#include <string>
auto capitalizeFirstLetter(std::string text) {
for (bool newWord = true; auto &&i : text) {
i = newWord ? std::toupper(i) : i;
newWord = std::isspace(i);
}
return text;
}
int main() {
std::string sentence;
while (std::getline(std::cin, sentence))
std::cout << capitalizeFirstLetter(sentence) << std::endl;
}
Sample Run

isalpha causing a "Debug Assertion Failed" in c++

I have a short program designed to count the number of consonants in a string by first testing to see if the character in the array is an alpha character (to skip any white space or punctuation). I keep getting a Debug Assertion Failed for my "if (isalpha(strChar))" line of code.
"strChar" is a variable that is assigned the char value in a for loop
Sorry if this is a remedial issue, but I'm not sure where I'm going wrong. Thanks in advance for any help!
#include <iostream>
#include <cctype>
using namespace std;
int ConsCount(char *string, const int size);
int main()
{
const int SIZE = 81; //Size of array
char iString[SIZE]; //variable to store the user inputted string
cout << "Please enter a string of no more than " << SIZE - 1 << " characters:" << endl;
cin.getline(iString, SIZE);
cout << "The total number of consonants is " << ConsCount(iString, SIZE) << endl;
}
int ConsCount(char *string, const int size)
{
int count;
int totalCons = 0;
char strChar;
for (count = 0; count < size; count++)
{
strChar = string[count];
if (isalpha(strChar))
if (toupper(strChar) != 'A' || toupper(strChar) != 'E' || toupper(strChar) != 'I' || toupper(strChar) != 'O' || toupper(strChar) != 'U')
totalCons++;
}
return totalCons;
}
I guess the problem is that you are always looping through 81 characters even though less were entered. That results in some random data fed to isalpha().
Anyway, I would change to code to use std::string instead of char iString[SIZE] to get the actual length of the input text.
The function ConsCount(char* string, const int size) should be like this:
int ConsCount(char *string, const int size)
{
int consCount = 0;
char* begin = string;
for (char* itr = begin; *itr != '\0'; ++itr)
{
if (isalpha(*itr)) {
char ch = toupper(*itr);
switch(ch) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
break; // If ch is any of 'A', 'E', 'I', 'O', 'U'
default:
++consCount;
}
}
}
return consCount;
}
As you can see I replaced the if statement with switch for better readability and using char* as a iterator to iterate the string. You can remove the unused parameter int size in your code.
And also I suggest you to use std::string for the safe-code. It also provides you a iterator class to iterate over the std::string.
int ConsCount(char *string, const int size)
{
int consCount = 0;
char* begin = string;
for (char* itr = begin; *itr != '\0'; ++itr)
{
if (isalpha(*itr)) {
char ch = toupper(*itr);
switch(ch) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
break; // If ch is any of 'A', 'E', 'I', 'O', 'U'
default:
++consCount;
}
}
}
return consCount;
try this
}

Write a c++ program that finds the number of vowels used in an string

Write a c++ program that finds the number of vowels used in an string.
For the above problem I written a program as follows:
int main()
{
char x[10];
int n,i,s=0;
cout<<"Enter any string\n";
cin>>x;
n=strlen(x);
for(i=0;i<n;++i)
{
if(x[i]=='a'||x[i]=='e'||x[i]=='i'||x[i]=='o'||x[i]=='u')
{
s=s+1;
}
}
cout<<s;
return 0;
}
Output of the program is as:
Enter any string elephant 3
Here in 'elephant' at three places vowels are used but the total number of vowels used is 2(e and a) not 3
I am asking to improve the program so that it counts the total number of vowels and print the total number.(e.g. in case of elephant it must give 2)
Make another array(), with 5 index, like
vowels[5] = array(0,0,0,0,0);
Then make if else if, with eache vowel, and add
if(x[i] == 'a') vowels[0] =1;
elseIf(x[i] == 'e') vowels[1] =1;
etc, and then check if vowels array is set to 1 or 0, and count only, these which are 5.
int count=0;
foreach vowels as item {
if(item == 1) count++
}
return count;
The easiest solution would be to just insert each vowel you see
into an std::set, and use its size function when you're
done.
And for heaven's sake, use a table lookup to determine whether
something is a vowel (and put the logic in a separate function,
so you can correct it when you need to handle the "sometimes y"
part).
Alternatively, without using the standard algorithms:
int charCount[UCHAR_MAX + 1];
// and for each character:
++ charCount[static_cast<unsigned char>( ch )];
(Of course, if you're using C++, you'll read the characters
into an std::string, and iterate over that, rather than having
an almost guaranteed buffer overflow.)
Then, just look at each of the vowels in the table, and count
those which have non-zero counts:
int results = 0;
std::string vowels( "aeiou" ); // Handling the sometimes "y" is left as an exercise for the reader.
for ( auto current = vowels.begin(); current != vowels.end(); ++ current ) {
if ( charCount[static_cast<unsigned char>( *current )] != 0 ) {
++ results;
}
}
Of course, neither of these, implemented naïvely, will handle
upper and lower case correctly (where 'E' and 'e' are the same
vowel); using tolower( static_cast<unsigned char>( ch ) ) will
solve that.
EDIT:
Since others are proposing solutions (which are only partially
correct):
bool
isVowel( unsigned char ch )
{
static std::set<int> const vowels{ 'a', 'e', 'i', 'o', 'u' };
return vowels.find( tolower( ch ) ) != vowels.end();
}
int
main()
{
std::string text;
std::cout << "Enter any word:";
std::cin >> text;
std::set<unsigned char> vowelsPresent;
for ( unsigned char ch: text ) {
if ( isVowel( ch ) ) {
vowelsPresent.insert( tolower( ch ) );
}
}
std::cout << vowelsPresent.size() << std::endl;
}
Separating the definition of a vowel into a separate function is
practically essential in well written code, and at the very
least, you need to mask differences in case. (This code also
punts on the question of "y", which would make isVowel several
orders of magnitude more difficult. It also ignores characters
outside of the basic character set, so "naïve" will report two
different vowels.)
Sets already eliminate duplicates, so instead of counting vowels as you encounter them, add them into a set. Then, at the end, count the number of [non-duplicate] vowels by querying the set for its size.
#include <set>
#include <string>
#include <iostream>
int main()
{
std::string x;
int n = 0;
std::set<char> vowels;
std::cout << "Enter any string\n";
std::cin >> x;
n = x.size();
for (int i = 0; i < n; ++i)
if (x[i] == 'a' || x[i] == 'e' || x[i] == 'i' || x[i] == 'o' || x[i] == 'u')
vowels.insert(x[i]);
std::cout << vowels.size() <<'\n';
}
Live demo
g++-4.8 -std=c++11 -O2 -Wall -pedantic -pthread main.cpp && echo "elephant" | ./a.out
Enter any string
2
Note that I also exchanged your use of fixed-sized arrays with an std::string, so that you're not at risk of dangerous circumstances when someone happens to input more than 9 characters.
I find a really easy way to solve this problem is by using map <char, int>. This will allow you to make pairs, indexed by a char, ie. the vowels, and connect an integer counter to them.
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
map <char, int> vowels;
int n,i,s=0;
string x;
cout<<"Enter any string\n";
cin>>x;
for(i=0;i< x.length();++i)
{
if(x[i]=='a'||x[i]=='e'||x[i]=='i'||x[i]=='o'||x[i]=='u')
{
vowels[x[i]]++;
}
}
for (map<char,int>::const_iterator print = vowels.begin(); print != vowels.end(); ++print){
cout << print -> first << " " << print -> second << endl;
}
return 0;
}
For the string elephant we would get the following output:
a 1
e 2
By saying vowels[x[i]]++; we are adding the found vowel into our map, if it already has not been added, and incrementing its paired int by one. So when we find the first e it will add e to our map and increment its counter by one. Then it will continue until it finds the next e and will see that it already has that indexed, so it will simply increment the counter to 2. This way we will avoid the problem with duplicates. Of course, if you wanted to get a single digit we could just print out the size of our map:
cout << vowels.size() << endl;
Okay. My turn. To handle both upper and lower cases we convert to just lower:
std::string x("Elephant");
std::transform(x.begin(), x.end(), x.begin(), std::function<int(char)>(std::tolower));
Now remove duplicates:
std::sort(x.begin(), x.end());
std::unique(x.begin(), x.end());
Now to count the vowels. I was hoping for something specific in locale but alas... Never mind we can create our own. Bit more complex, but not overly:
struct vowel : public std::ctype<char>
{
static const mask* make_table()
{
static std::vector<mask> v(classic_table(), classic_table() + table_size);
v['a'] |= upper;
v['e'] |= upper;
// etc.
return &v[0];
}
vowel(std::size_t refs = 0) : ctype(make_table(), false, refs){}
};
While I am sure you can create your own but can't quite figure out how going by the documentation on cppreference so I say lower case vowels are uppercase. With the earlier call to std::tolower this should be safe.
With this we can use it easily like:
int i = std::count_if(x.begin(), x.end(), [](const char c)
{
return std::isupper(c, std::locale(std::locale(""), new vowel));
});
std::cout << "Number of vowels:" << i << std::endl;
However I am not particularly happy with the two std::locale next each other.
Easiest solution I can think of would be an array of bools representing each vowel and whether or not they've been counted.
bool vowelCounted[5] = { false };
Now, as you count the vowels:
if (x[i]=='a' && !vowelCounted[0]) {
vowelCounted[0] = true;
s += 1;
} else if (x[i]=='e' && !vowelCounted[1]) {
vowelCounted[1] = true;
s += 1;
}
And just repeat this structure for all 5 vowels.
The readability can be improved by using an enum rather than 0, 1, 2, 3, 4 for your indices... but you're using variables named x[] and s, so it's probably fine...
If you use one of the standard containers (vector, list) add your vowels in there, do the same check as you're doing now, if it exists then remove it. When you're finished get the number of remaining elements, your answer will be the original count for the vowels minus the the remaining elements.
try this
for( string text; getline( cin, text ) && text != "q"; )
{
set< char > vowels;
copy_if( begin(text), end(text), inserter( vowels, begin(vowels) ),
[]( char c ) { return std::char_traits< char >::find( "aeiou", 5, c ) != nullptr; } );
cout << "the string [" << text << "] contains " << vowels.size() << " vowels" << endl;
}
You need the includes string, iostream, set, algorithm and iterator.
What do You want to do with the upper ones "AEIOU" ?
You can create this:
std::vector< char> vowels;
And put into it all vowels that you meet while iterating through the string:
if(x[i]=='a'||x[i]=='e'||x[i]=='i'||x[i]=='o'||x[i]=='u')
vowels.push_back( x[i]);
Then you can sort this and eliminate duplicates:
std::sort( vowels.begin(), vowels.end());
std::vector< char> vowels_unique( vowels.size());
std::vector< char>::iterator it;
it = std::unique_copy( vowels.begin(), vowels.end(), vowels_unique.begin());
vowels_unique.resize( std::distance( vowels_unique.begin(), it));
Even better, use a set property - it holds unique data, like this:
std::set< char> unique_vowels;
if(x[i]=='a'||x[i]=='e'||x[i]=='i'||x[i]=='o'||x[i]=='u')
unique_vowels.insert( x[i]);
//...
int unique = unique_vowels.size();
C++ Code Snippet :
#include <bits/stdc++.h>
using namespace std;
int main()
{
char s[100];
int cnt;
cnt=0;
cin>>s;
for(int i=0;s[i];i++)
{
char c =s[i];
if(s[i]=='A' || s[i] =='E' || s[i]=='I' ||s[i]=='O'|| s[i]=='U') cnt++;
else if(s[i]=='a' || s[i] =='e' || s[i]=='i'||s[i]=='o' || s[i]=='u') cnt++;
}
cout<<cnt<<endl;
return 0;
}
Version utilizing std::find() and std::transform():
#include <string>
#include <iostream>
#include <algorithm>
using std::string;
using std::cout;
using std::cin;
using std::getline;
using std::transform;
int main()
{
cout << " Type sentence: ";
string sentence;
getline(cin, sentence);
transform(sentence.begin(), sentence.end(), sentence.begin(), toupper);
string vowels = "AEIOU";
size_t vowCount = 0;
for (int i = 0; i < vowels.length(); ++i)
{
if (sentence.find(vowels[i], 0) != string::npos)
{
++vowCount;
}
}
cout << "There is " << vowCount << " vowels in the sentence.\n";
return 0;
}
PROS
std::find() searches just for first occurrence of given vowel so there is no iteration over rest of the given string
using optimized algorithms from std
CONS
std::transform() transforms each lower-case letter regardless of its "vowelness"
#include<iostream> //std::cout
#include<string> //std::string
#include<cctype> //tolower()
#include<algorithm> //std::for_each
using namespace std;
int main()
{
string s;
getline(cin, s);
int count = 0;
for_each(s.begin(), s.end(), [&count](char & c) //use of lambda func
{
c = tolower(c); //you can count upper and lower vowels
switch (c)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
count++;
break;
}
});
cout << count << endl;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
char vowels[5] = {'a','e','i','o','u'};
char x[8] = {'e','l','e','p','h','a','n','t'};
int counts[5] = {0,0,0,0,0};
int i,j;
for(i=0;i<8;i=i+1)
{
for(j=0;j<5;j=j+1)
{
if(x[i]==vowels[j])
{
counts[j] = counts[j] + 1;
}
}
}
for(i=0;i<5;i=i+1)
{
cout<<counts[i]<<endl;
}
return 0;
}
Since I was using the example of 'elephant' so I just initialized that.
If still any modification can be made then please edit it and make it more user friendly.

Go word-by-word through a text file and replace certain words

My intended program is simple: Take each word of a text file and replace it with asterisks if it's a swear word. For instance, if the text file was "Hello world, bitch" then it would be modified to "Hello world, *****".
I have the tool for taking a word as a string and replacing it with asterisks if needed. I need help setting up the main part of my program because I get confused with all the fstream stuff. Should I instead make a new file with the replaced words and then overwrite the previous file?
#include <iostream>
#include <string>
#include <fstream>
const char* BANNED_WORDS[] = {"fuck", "shit", "bitch", "ass", "damn"};
void filter_word(std::string&);
void to_lower_case(std::string&);
int main (int argc, char* const argv[]) {
return 0;
}
void filter_word(std::string& word) {
std::string wordCopy = word;
to_lower_case(wordCopy);
for (int k = 0; k < sizeof(BANNED_WORDS)/sizeof(const char*); ++k)
if (wordCopy == BANNED_WORDS[k])
word.replace(word.begin(), word.end(), word.size(), '*');
}
void to_lower_case(std::string& word) {
for (std::string::iterator it = word.begin(); it != word.end(); ++it) {
switch (*it) {
case 'A': *it = 'a';
case 'B': *it = 'b';
case 'C': *it = 'c';
case 'D': *it = 'd';
case 'E': *it = 'e';
case 'F': *it = 'f';
case 'G': *it = 'g';
case 'H': *it = 'h';
case 'I': *it = 'i';
case 'J': *it = 'j';
case 'K': *it = 'k';
case 'L': *it = 'l';
case 'M': *it = 'm';
case 'N': *it = 'n';
case 'O': *it = 'o';
case 'P': *it = 'p';
case 'Q': *it = 'q';
case 'R': *it = 'r';
case 'S': *it = 's';
case 'T': *it = 't';
case 'U': *it = 'u';
case 'V': *it = 'v';
case 'W': *it = 'w';
case 'X': *it = 'x';
case 'Y': *it = 'y';
case 'Z': *it = 'z';
}
}
}
The usual solution to modifying a file is to generate a new
file, then delete the old and rename the new. In your case,
because your replacement text has exactly the same length as
your new text, you can do it in place, with something like:
std::fstream file( fileName, ios_base::in | ios_base::out );
if ( !file.is_open() ) {
// put error handling here...
std::string word;
std::fstream::pos_type startOfWord;
while ( file.peek() != std::fstream::traits::eof() ) {
if ( ::isalpha( file.peek() ) ) {
if ( word.empty() ) {
startOfWord = file.tellg();
}
word += file.get();
} else {
if ( !word.empty() ) {
if ( std::find_if( banned.begin(), banned.end(), CaseInsensitiveCompare() ) ) {
file.seekp( startOfWord );
file.write( std::string( word.size(), '*').c_str(), word.size() );
}
word.clear();
}
file.get();
}
}
with:
struct CaseInsensitiveCompare
{
bool operator()( unsigned char lhs, unsigned char rhs ) const
{
return ::tolower( lhs ) == ::tolower( rhs );
}
bool operator()( std::string const& lhs, std::string const& rhs ) const
{
return lhs.size() == rhs.size()
&& std::equal( lhs.begin(), lhs.end(), rhs.begin(), *this )
}
};
The tellg and seekp probably aren't the most efficient
operations around, but if the file is large, and you don't have
to seek too often, it may still be more efficient than writing
a completely new file. Of course, if efficiency is an issue,
you might want to consider mmap, and doing the job directly in
memory. That would certainly be the most efficient, and
probably the easiest to code as well. But it would be platform
dependent, and would require extra effort to handle files larger
than your available address space.
Also, for the future (since there is a standard tolower that
you can use), when doing code translation (which is really what
to_lower_case does), use a table. It's much simpler and
faster:
char
to_lower_case( char ch )
{
char translationTable[] =
{
// ...
};
return translationTable[static_cast<unsigned char>( ch )];
}
If you don't want your code to be dependent on the encoding, you
can use dynamic initialization:
if ( !initialized ) {
for ( int i = 0; i <= UCHAR_MAX; ++ i ) {
translationTable[i] = i;
}
static char const from[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static char const to[] = "abcdefghijklmnopqrstuvwxyz";
for ( int i = 0; i != sizeof(from); ++ i ) {
translationTable[from[i]] = to[i];
}
}
This is not a good idea for things like tolower, however;
you would have to know all of the possible upper case
characters, which in turn depends on the encoding. (The
functions in <ctype.h> do do something like this. And
redefine the translation table each time you change locale.) It
can be useful for other types of mappings.
I think you need a code to read file word by word and replace if the word is one of BANNED_WORDS
So here is a solution for main():
int main()
{
std::vector <std::string> words; // Vector to hold our words we read in.
std::string str; // Temp string to
std::cout << "Read from a file!" << std::endl;
std::ifstream fin("thisfile.txt"); // Open it up!
while (fin >> str) // Will read up to eof() and stop at every
{ // whitespace it hits. (like spaces!)
words.push_back(str);
}
fin.close(); // Close that file!
std::ofstream fout("temp.txt"); // open temp file
for (int i = 0; i < words.size(); ++i)
{ // replace all words and add it to temp file
filter_word(words.at(i));
fout<<words.at(i) << endl;
}
// Add code for replace the file
return 0;
}
And for to_lower_case() you can use
#include <ctype.h>
// ...
*it = tolower(*it);
As suggested by Paul Evans
Hope this will help you

string conversion c++

I have a string and the first element is for example 'a'. I already declared a variable called a ( so int a=1 for example). My question now is, how can I convert the whole string to numbers (a=1,b=2,c=3,...z=26)? Example:
string str="hello"; this has to be changed to "85121215" and then changed to 85121215.
// transformation itself doesn't care what encoding we use
std::string transform_string(std::string const &in, std::function<int(char)> op)
{
std::ostringstream out;
std::transform(in.begin(), in.end(),
std::ostream_iterator<int>(out),
op);
return out.str();
}
// the per-character mapping is easy to isolate
int ascii_az_map(char ch)
{
if (ch < 'a' || ch > 'z') {
std::ostringstream error;
error << "character '" << ch << "'=" << (int)ch
<< " not in range a-z";
throw std::out_of_range(error.str());
}
return 1 + ch - 'a';
}
// so we can support other encodings if necessary
// NB. ebdic_to_ascii isn't actually implemented here
int ebcdic_az_map(char ch)
{
return ascii_az_map(ebcdic_to_ascii(ch));
}
// and even detect the platform encoding automatically (w/ thanks to Phresnel)
// (you can still explicitly select a non-native encoding if you want)
int default_az_map(char ch)
{
#if ('b'-'a' == 1) && ('j' - 'i' == 1)
return ascii_az_map(ch);
#elif ('j'-'i' == 8)
return ebcdic_az_map(ch);
#else
#error "unknown character encoding"
#endif
}
// use as:
std::string str = "hello";
std::string trans = transform_string(str, ascii_az_map);
// OR ... transform_string(str, ebcdic_az_map);
Note that since the per-character mapping is completely isolated, it's really easy to change the mapping to a lookup table, support different encodings etc.
Your definition is a bit small:
"hello" = "85121215
h = 8
e = 5
l = 12
o = 15
I assume you mean that
a = 1
b = 2
...
z = 26
in which case it is not that hard:
std::string meh_conv(char c) {
switch(c) { // (or `switch(tolower(c))` and save some typing)
case 'a': case 'A': return "1";
case 'b': case 'B': return "2";
....
case 'z': case 'Z': return "26";
....
// insert other special characters here
}
throw std::range_error("meh");
}
std::string meh_conv(std::string const &src) {
std::string dest;
for (const auto c : s)
dest += meh_conv(c);
return dest;
}
or use std::transform():
#include <algorithm>
std::string dest;
std::transform (src.begin(), src.end(), back_inserter(dest),
meh_conv)
(doesn't work for different incoming and outgoing types, at least not as is)
Addendum.
You possibly want to parametrize the replacement map:
std::map<char, std::string> repl;
repl['a'] = repl['A'] = "0";
repl[' '] = " ";
std::string src = "hello";
std::string dest;
for (const auto c : src) dest += repl[c];
I wrote you a simple example. It creates a map what contains the a-1, b-2, c-3 ... pairs. Then concatenate the values using a stringstream:
#include <iostream>
#include <map>
#include <sstream>
int main()
{
std::string str = "abc";
std::map<char,int> dictionary;
int n = 1;
for(char c='a'; c<='z'; c++)
dictionary.insert(std::pair<char,int>(c,n++));
//EDIT if you want uppercase characters too:
n=1;
for(char c='A'; c<='Z'; c++)
dictionary.insert(std::pair<char,int>(c,n++));
std::stringstream strstream;
for(int i=0; i<str.size(); i++)
strstream<<dictionary[str[i]];
std::string numbers = strstream.str();
std::cout<<numbers;
return 0;
}
C++ experts probably going to kill me for this solution, but it works ;)
Easy Approach,
you can find mod of char with 96 (ASCII value before a), as result it will always give you values in range 1-26.
int value;
string s;
cin>>s;
for(int i=0; i<s.size();i++){
value = s[j]%96;
cout<<value<<endl;
}