I am looking for a way to count the characters of a word, phrase or text in Spanish.
For example:
cout << "Cantidad de letras: " << letters_counted( "¿Hola, cómo estás?" ) << endl;
The result should be:
Cantidad de letras: 13
I am not finding a way to compare letters with accents, is there a way?
This is an attempt that failed me:
int count=0; txt="Hola, cómo estás";
regex rx( "[a-zA-ZñÑáéíóúÁÉÍÓÚ]" );
for( sregex_iterator it( txt.cbegin(), txt.cend(), rx ); it!=sregex_iterator();
++it ) count++;
cout << count << endl;
Instead of displaying 13, which is the number of letters, it returns 15.
I don't understand how to treat extended characters, like vowels with accents, á, é, í, ó, ú and ñ .
This is another try, the algorithm is similar to @AngelAngel.
int letters_counted_in_text( std::string const&text ) {
count = 0
string abc = "abcdefghijklmnñopqrstuvwxyzáéíóú"
"ABCDEFGHIJKLMNÑOPQRSTUVWXYZÁÉÍÓÚ";
for( unsigned i=0; i<text.length(); ++i )
for( unsigned j=0; j<abc.length(); ++j )
if( text.at( i )==abc.at( j ) )
{
count++;
j=abc.length();
}
return count;
}
But it also returns 15 letters when it should be 13, like " Hello, how are you ".
Is there possibility to use u16string or wstring? To treat the letters of the Spanish alphabet.
I have seen that I modified your question, I will delete my previous answer, I will leave some clarifications about why those codes worked
Well to the mess that sure is in a hurry.
From your question:
testideone
changes:
string
bywstring
and addL
:wstring txt = L"Hola, cómo estás";
regex
bywregex
and addL
:wregex rx( L"[a-zA-ZñÑáéíóúÁÉÍÓÚ]" );
sregex_iterator
bywsregex_iterator
for( wsregex_iterator...
sregex_iterator();
bywsregex_iterator();
it!=wsregex_iterator();
From your question:
changes:
std::string const&text
bystd::wstring const&text
.
string
bywstring
and addL
:.
I think this code is more or less what you are looking for, it counts the characters if they are in the dictionary:
I leave you these codes because I was not very clear about what you were asking, (surely it was me when reading, it was difficult for me to understand what you wanted)
With this code you can count the number of times a character appears as long as it is in the dictionary.
With this code you can count the number of different characters, as long as they are in the dictionary.
It is more than likely that the above codes can be optimized but I think that this will give you a better understanding of what they do.
You can try something similar if you want to count characters:
The
if
insidefor
is responsible for counting how many spaces there are within the string and then subtracting them from the length of the string.http://www.cplusplus.com/reference/string/string/erase/ http://www.cplusplus.com/reference/string/string/at/