c++ ocurrence of a std::string inside another std::string - c++

i am tryng to count the ocurrence of a std::string inside another std::string using this:
static int cantidadSimbolos(const std::string & aLinea/*=aDefaultConstString*/,
const std::string & aSimbolo/*=aDefaultSimbolSeparador*/)
{
if(aSimbolo.empty()) return 0;
if (aLinea.empty()) return 0;
int aResultado=0;
//This is the line that the compiler doesnt like
aResultado=std::count(aLinea.begin(),aLinea.end(),aSimbolo);
return aResultado;
}
but the compiler doesnt like it, this is the error that the compiler emits:
error: no match for ‘operator==’ in
‘_first._gnu_cxx::__normal_iterator<_Iterator,
_Container>::operator* >() == __value’
any help??
thx in advance!

The following code will find the count of the non-overlapping occurrences of a given string.
using namespace std;
static int countOccurences(const string & line, const string & symbol) {
if (symbol.empty()) return 0;
if (line.empty()) return 0;
int resultCount = 0;
for (size_t offset = line.find(symbol); offset != string::npos;
offset = line.find(symbol, offset + symbol.length()))
{
resultCount++;
}
return resultCount;
}
int main(int argc, const char * argv[])
{
cout << countOccurences("aaabbb","b") << endl;
return 0;
}
The find function will return either an iterator to the first element of the value it matches to or return 'last' hence string::npos. This ensures no overlap with offset + symbol.length().
I did my best to translate the variables to English for readability for English users.

Related

How to use pointer to string in cpp?

I am studying pointers in C++. I have studied call by value and call by reference concept. I am trying to create a function to reverse a string which accepts a pointer to string and the size of string. The code is as follow
void reverse(string* str, int size)
{
int start = 0;
int end = size - 1;
while(start < end)
{
swap(*str[start++], *str[end--]);
}
}
int main()
{
string str = "Something";
reverse(&str, str.length());
cout << "Reversed string: " << str << endl;
return 0;
}
I am getting this error:
error: no match for ‘operator*’ (operand type is ‘std::string’ {aka
‘std::__cxx11::basic_string’})
12 | swap(*str[start++], *str[end--]);
I don't want to use the character array, is there way to do it?
Someone please explain, what's wrong in my code. Thank you.
Here is the simple fix. You don't need to change anything except a few lines.
#include <iostream>
#include <algorithm>
#include <cstring>
void reverse( std::string* str ) // no need to pass size to this function
{
int start = 0;
int end = str->length() - 1; // get the length of str like this
char* ptrToCharArray = const_cast<char*>( str->c_str() ); // gets the pointer to str's internal buffer
while ( start < end )
{
std::swap( ptrToCharArray[start++], ptrToCharArray[end--] ); // no need to use * operator anymore
}
}
int main()
{
std::string str = "Something";
reverse( &str );
std::cout << "Reversed string: " << str << std::endl;
return 0;
}
Output is:
Reversed string: gnihtemoS
Hopefully, this helps you.
Just need a little bit of change in your code
Change this *str[start++] to (*str).at(start++)
void reverse(string* str, int size)
{
int start = 0;
int end = size - 1;
while(start < end)
{
swap((*str).at(start++),(*str).at(end--));
}
}
int main()
{
string str = "Something";
reverse(&str, str.length());
cout << "Reversed string: " << str << endl;
return 0;
}
Note that there is no need to pass the size of the string as an argument to the function. You can use the member function std::string::size for that purpose as shown below:
Version 1: Passing pointer to string as argument
#include <iostream>
#include <algorithm>
void reverse(std::string *str)
{
int n=(*str).size()-1;//dereference the pointer and use size member function on the resulting string object
for(int i=0;i<((*str).size()/2);i++){
//Using the swap method to switch values at each index
std::swap((*str).at(i),(*str).at(n)); //note this can also be written as std::swap((*str)[i],(*str)[n]);
n = n-1;
}
}
int main()
{
std::string myString = "myString";
reverse(&myString);
std::cout<<"Reversed string is: "<<myString<<std::endl;
return 0;
}
In version 1, *(str) gives us a std::string type object. Next we call size member function on this std::string object. Similarly we can call the std::string::at member function on this std::string object.
Version 2: Passing reference to string as argument
#include <iostream>
#include <algorithm>
void reverse( std::string &str)
{
int n=str.size()-1;
for(int i=0;i<(str.size()/2);i++){
//Using the swap method to switch values at each index
std::swap(str.at(i),str.at(n));
n = n-1;
}
}
int main()
{
std::string myString = "myString";
reverse(myString);
std::cout<<"Reversed string is: "<<myString<<std::endl;
return 0;
}

Counting the occurrences of every char of of one string in another string

I am trying to write a function that takes two strings as arguments and returns the total count of how many times each character of the second string appears in the first.
For example, i = count("abracadabra", "bax"); would return 7.
I am looking to utilize the STL. I have written the following function that counts how many occurrences of one char happens in a string, but calling this function on a loop to solve the problem above seems quite inefficient.
int count(const std::string& str, char c)
{
int count = 0;
size_t pos = str.find_first_of(c);
while (pos != std::string::npos)
{
count++;
pos = str.find_first_of(c, pos + 1);
}
return count;
}
You can modify the count function to accept a std::string as second argument and then loop one character at a time and use std::count to count the number of occurrences of each character and increment the overall count
#include <iostream> // std::cout
#include <string> // std::string
#include <algorithm> // std::count
int count(const std::string& search, const std::string& pattern)
{
int total = 0;
for(auto &ch : pattern) {
total += std::count(search.begin(), search.end(), ch);
}
return total ;
}
int main ()
{
std::string hay("abracadabra");
std::string needle("bax");
std::cout << count(hay, needle) << std::endl;
return 0;
}

C++ error: expected ',' or ';' before '{' token when their is

I am trying to create a function that will return the alphabet position of a letter that is passed into the function
for example
cout<<getPosition('l')
would return the integer 12. I am fairly certain I have got the logic correct however I am having some trouble with the syntax. I found many similar questions however I still was not able to solve the problem.
Any help appreciated
#include <iostream>
using namespace std;
int getPosition(letter)
{
int pos = 0;
const char alphabet[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
for (int counter=0; counter!=26; counter++)
{
if (alphabet[counter] == letter)
{
pos = counter;
break;
}
}
return pos;
}
int main()
{
string letter = 'r';
cout << posInAlpha(letter);
return 0;
}
You are mixing std::string and char, while you don't need the first. Moreover, your main() uses a function not declared. Furthermore, your function's parameter lacks it's type. Your compiler should be pretty explanatory for these. I modified your code to get the desired behavior; please take a moment or two understanding what had to be modified here:
#include <iostream>
using namespace std;
// Returns the index of 'letter' in alphabet, or -1 if not found.
int getPosition(char letter)
{
int pos = -1;
const char alphabet[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
for (int counter=0;counter!=26;counter++)
{
if (alphabet[counter]==letter)
{
pos=counter;
break;
}
}
return pos;
}
int main()
{
char letter='r';
cout<<getPosition(letter);
return 0;
}
Output:
17
I initialized pos to -1, in case letter does not belong in the alphabet. Otherwise the function would return 0, meaning that a was the answer.
PS: If letter was an std::string, then your comparison with every letter of the alphabet would produce a compilation error, since the types do not match.
it all begins here
int getPosition(letter)
{
this function is not right declared/defined, letter must be a type and you just gave none...
assuming this
char letter = 'r';
cout << posInAlpha(letter);
that letter must be a char and the function posInAlpha should be renamed to getPosition
it all looks like you are mixing std::strings and chars,
your final fixed code should look like:
#include <iostream>
using namespace std;
int getPosition(char& letter)
{
int pos = 0;
const char alphabet[26] = { 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };
for (int counter = 0; counter != 26; counter++)
{
if (alphabet[counter] == letter)
{
pos = counter;
break;
}
}
return pos;
}
int main()
{
char letter = 'r';
cout << getPosition(letter);
cin.get();
return 0;
}
which prints 17 for the given char 'r'
#include <iostream>
int getPosition( char c )
{
c |= 0x20; // to lower
return ( c < 'a' || c > 'z' )
? -1
: c - 'a';
}
int main()
{
std::cout << getPosition( 'R' );
return 0;
}
Demo

Find string inside 2D char array in C

I am trying to find a string which is inside 2D char array and return it's index. For example:
char idTable[255][32];
char tester[] = { 't','e','s','t','e','r','\0' };
memcpy(idTable[43], tester, 7);
uint8_t id = getID(name[0]);
//name is returned from function "char **name = func();"
//but I have the same results when I try using normal char array...
I've had partial success with the first part of the below code, but it is finding a match if a part of the word is the same (one, oneTwo). If I add "else if" to the first "if" it always goes to the "else if".
The rest of the file prints different results for
printf("idTable string lenght:\t %u\n", strlen(idTable[index]));
and
printf("foundMatch string lenght:\t %u\n", strlen(foundMatch));
, unless I add printf("Index:\t %i\n", index);.
uint8_t getID(char *name) {
printf("\nInserted name:\t %s\n", name);
uint8_t index;
for (uint8_t r = 0; r < 255; r++) {
if (strstr(idTable[r], name) != NULL) {
printf("Found '%s' in position:\t %d\n", name, r);
index = r;
}
}
printf("Index:\t %i\n", index); // THIS LINE
char foundMatch[strlen(idTable[index])];
printf("idTable string lenght:\t %u\n", strlen(idTable[index]));
for (uint8_t c=0; c<strlen(idTable[index]); c++) {
foundMatch[c] = idTable[index][c];
}
printf("foundMatch string lenght:\t %u\n", strlen(foundMatch));
if (strcmp(foundMatch, nodeName) == 0) {
printf("Confirmed\n");
return index;
} else {
printf("Second test failed\n");
return 0;
}
}
Why am I getting this strange results and is there a better way to do this?
I don't know how you are initializing your idTable entries, but if you are using the method that you showed at the start of the question you'll have problems. You can't assume all of the space reserved by idTable is initialed to 0's, so idTable[43] isn't a null terminated string. Therefore idTable[43] need not compare equal to the null terminated string "tester".
Also your getID function doesn't return anything despite its signature. So it won't even compile as-is.
Here's a solution in actual C++, not C.
std::array<std::string, 255> idTable;
idTable.at(43) = "tester";
std::pair<std::size_t, std::size_t> findInIdTable(std::string const& what) {
for (unsigned i = 0; i < idTable.size(); ++i) {
std::size_t pos = idTable.at(i).find(what);
if (pos != std::string::npos) {
return std::make_pair(i, pos);
}
}
// if the code reaches this place, it means "not found". Choose how you want to deal with it
// my personal suggestion would be to return std::optional<std::pair<...> instead.
}
If you want to discard the pos value, it's easy to change as well.
Live On Coliru
In the category: Use C++
Of course, use std::array<char, 32> or std::string if possible. I stuck with your choices for this answer:
Live On Coliru
#include <algorithm>
#include <iostream>
#include <cstring>
char idTable[255][32] = { };
int main() {
using namespace std;
// initialize an entry
copy_n("tester", 7, idTable[43]);
// find match
auto match = [](const char* a) { return strcmp(a, "tester") == 0; };
auto index = find_if(begin(idTable), end(idTable), match) - idTable;
// print result
cout << "match at: " << index;
}
Prints
match at: 43
You need to add a nul to the end of the foundMatch array after copying in the idTable row:
foundMatch[strlen(idTable[index])] = '\0';
right before the 'foundMatch string lenght' (length) message.
strlen is an expensive function that walks the string every time. You should call that once, store it in a local variable, then reference that variable rather than calling strlen repeatedly.

Find occurrences of all substrings in a given string

I use a simple string function strstr to find the first occurrence of a string in some text. I used the following code to count the number of unique words in a text.
for (int i = 0; i < 24; i++)
{
if (strstr(text, ops[i]))
{
op++;
}
}
But I want to find the occurrence of all the sub strings in the program. How can I do this?
strstr() is for the C-style string, if you are really using C++, std::string and its member function would be much more convenient.
#include <string>
#include <iostream>
using namespace std;
int main()
{
string s("hello hello");
int count = 0;
size_t nPos = s.find("hello", 0); // first occurrence
while(nPos != string::npos)
{
count++;
nPos = s.find("hello", nPos + 1);
}
cout << count;
};
You can use one of the std::string find methods which would be easier (and safer), but if you really need to use strstr:
int _tmain(int argc, _TCHAR* argv[])
{
const char test[] = "this test is a test";
const char subStr[] = "test";
const char* pCurrent = strstr( test, subStr );
while( pCurrent != NULL )
{
std::cout << "found" << std::endl;
pCurrent++;
pCurrent = strstr( pCurrent, subStr );
}
return 0;
}
This just increments the point where the last sub string was found. Note that you should do the normal string length, NULL and safety checks.