There are a few issues here:
-
Your program fails to compile because of the misplaced semi-colon in
cout<<"\nNew String 2 is :";<<b -
Your program crashes at
strcpy(a,x);because you’re copying intoawhich is uninitialised – it has no memory allocated. You’d need to callnewonafor this to work, which would also mean you’d need to know the size of the array required (another parameter for the function probably). -
Using
std::stringandstd::wstringis almost always preferable to dealing with raw char arrays. See this question for example. I see you’d probably already considered it since you’ve got#include <string> -
Since you’re required to perform identical operations on differing types, I suspect the point of the exercise might have been to use templates.
-
You said
getNiCountshould return the number of occurrences…yet your
getNiCountdoesn’t return anything. -
using namespace std;is often considered bad practice. -
It’s generally worth favouring pre-increments rather than post-increments, although in this particular case, there’s no overhead.
To give you an example including the recommendations above:
#include <iostream>
#include <string>
template<typename StrType>
class MyClass {
public:
int getNiCount(const StrType& input) const;
void replaceNiWithNI(StrType& input) const;
};
template<typename StrType>
int MyClass<StrType>::getNiCount(const StrType& input) const {
int count = 0;
for (int i = 0; i < input.size() - 1; ++i) {
if (input[i] == 'N' && input[i + 1] == 'i')
++count;
}
return count;
}
template<typename StrType>
void MyClass<StrType>::replaceNiWithNI(StrType& input) const {
for (int i = 0; i < input.size() - 1; ++i) {
if (input[i] == 'N' && input[i + 1] == 'i')
input[i + 1] = 'I';
}
}
int main() {
const char* szTestString1 = "Ni nI NI nI Ni";
MyClass<std::string> ob1;
std::string testString1(szTestString1);
int count1 = ob1.getNiCount(testString1);
ob1.replaceNiWithNI(testString1);
std::cout << "Found " << count1 << " occurences of Ni in String 1. "
<< "New string: " << testString1 << '\n';
const wchar_t* szTestString2 = L"Ni nI NI nI Ni";
MyClass<std::wstring> ob2;
std::wstring testString2(szTestString2);
int count2 = ob2.getNiCount(testString2);
ob2.replaceNiWithNI(testString2);
std::wcout << L"Found " << count2 << L" occurences of Ni in String 2. "
<< L"New string: " << testString2 << '\n';
getchar();
return 0;
}
I’ve generally left the way you locate and replace the Ni chars as you had it. There are more sophisticated options available in the member functions of std::string and in <algorithm> library.
0
solved programming task ask [closed]