Using strlen to strikeout specified words in string - c++

Using the following function, I am able to pass in two strings (char *hide, char *phrase). The *phrase is the overall string and * hide is what words (can be repeated) have to be censored by replacing all letters in the word with '*'. It currently works so that it goes on to find the first letter of the *hide, then the second letter of the *hide word despite it not being next to each other in the string eg.
*phrase = 'hello my name is'
*hide = 'lame'
result = 'he*lo my n*** is'
{
int i, j=0;
int lengthPhrase = strlen(phrase);
int lengthCensor = strlen(hide);
for (i = 0; i < lengthPhrase; i++) {
if (phrase[i] == hide[j]) {
phrase[i] = '*';
j++;
}
}
}
Where is the issue so that it works correctly by striking out the whole words??
Thank you for your time.

Since I don't seem to understand your question, I thought of making a function for you to see if this is what you're looking for:
string phrase = "hello my name is"
string hide = "lame"
//strikeout function
void strikeout(string phrase, string hide)
{
for (int i = 0; i < hide.size(); i++)
{
for (int j = 0; j < phrase.size(); j++)
{
if (hide[i] == phrase[j])
{
phrase[j] = '*';
}
}
}
cout << phrase << endl;
}
Output based on your testcase: "h***o *y n*** is"

Related

Having Trouble With The Reversal of a String

class Solution {
public:
string reverseWords(string s) {
int previousWhiteSpace = 0;
for(int i = 0; i <= s.size(); i ++){
if(isspace(s[i]) || i == s.size()){
for(int j = previousWhiteSpace; j < i/2; j++){
char temp = s[j];
s[j] = s[i-1-j];
s[i-1-j] = temp;
}
previousWhiteSpace = i + 1;
}
}
return s;
}
};
Hi. So the goal of my function is to reverse the input of a string. So for example, if I am given "Let's take LeetCode contest" , my function should return "s'teL ekat edoCteeL tsetnoc" . However, currently my function is ONLY returning
"s'teL take LeetCode contest" . I have a counter which I indicate as previousWhiteSpace to keep track of the start of every new word that seems to work for the first word, but not the rest. Any help would be appreciated.
You can simply assign " " to the variable previousWhiteSpace and no need to increment. thus your code will detect white space automatically till the end of the string and will run the code after every white space. As you have assigned value 0 to it will only perform the result for the first word and it will terminate.

Adding a space before a character in a string C++ insert function

I am attempting to add space before a character in a string by using the insert function.
Can someone kindly explain why the following code does not work ?
for(int i = 0; i < line.length(); i++)
{
if(line[i+1] == '=')
{
line.insert(i, " ");
}
}
If you want to insert before = you can get the index of = directly and not the index of char followed by =. This could lead to out of bounds access.
Also, when you insert the space you extend your string by 1, that's ok but only if you also adjust the counter i, otherwise it will insert again and again and again before = resulting in infinite loop. Adjust your code in this manner:
for (int i = 0; i < line.length(); i++)
{
if (line[i] == '=')
{
line.insert(i++, " ");
}
}
The code seems fine except for one little detail:
Imagine you have a string with "test=something". When you iterate it, when i is 3 you will find the next character is an equals, so you put a space into it. Next iteration i will be 4, but you just added a space, so at i equals 5 there's the same equals sign. So you put another space and so on. TO fix this youy can try:
std::string line = "test=something";
for (int i = 0; i < line.length(); i++)
{
if (line[i + 1] == '=')
{
i++;
line.insert(i, " ");
}
}

Sorting out duplicates between 2 char arrays [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 6 years ago.
Improve this question
I'm struggling with an assignment for my class where we have to take input from the user into a char array (word) and take out the duplicates in the word inputted if needed. Comparing the array of the modified array (word) with the alphabet array (abc) to remove the repeated letters from the list. Once the duplicates are removed then just output the modified word followed by the new form of the alphabet into the newAbc array.
For example:
The word HELLO would first become HELO then after comparing to the alphabet the end output from the new array should be HELOABCDFGIJKMNPQRSTUVXYZ.
I'm stuck more on the for loops comparing the new word to the alphabet really.
char word[20], newAbc[40] = { '\0' };
char abc[27] = {'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'};
int i = 0, b = 1, n = 0, leng, dup;
//dup counts up the repeats but is established in the first portion of the program but i've excluded it as it works perfectly.
cout << "Please enter a word: ";
cin >> word;
leng = strlen(word);
b = 0;
n = leng - dup;
i = 0;
for (i = 0; i < n; i++)
{
for (b = 0; b < 27; b++)
{
if (newAbc[i] != abc[b])
{
newAbc[n] = abc[b];
n++;
}
}
}
for (i = 0; i < 27; i++)
cout << newAbc[i];
cout << endl;
return 0;
}
I'd appreciate any kind of insight on my mistakes.
The major problem for crash is that you are changing n inside for loop for iterating in newAbc. And your if condition will be true for at least 25 times so incrementing n by 25(minimum) in each iteration resulting in accessing out of bound memory(SEG-FAULT).
for (i = 0; i < n; i++)
{
for (b = 0; b < 27; b++)
{
if (newAbc[i] != abc[b]) // this condition is not correct
{ // this will be true atleast 25 times
newAbc[n] = abc[b]; // wrong memory access
n++; // here is the problem
}
}
}
Assuming that your duplicate counting works fine, below are the changes required:-
char word[20];
// FIXME: your new array should not contain no duplicate so size can be 27
char newAbc[40] = {'\0'};
// FIXME: simply can be char abc[27] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char abc[27] = {'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'};
cout << "Please enter a word: ";
cin >> word;
// dup counts up the repeats but is established in the first portion of
// the program but i've excluded it as it works perfectly.
// Lets say word = "HELLO"; so dup = 1, and newArray, should have "HELO"
memcpy(newAbc, "HELO", 4); // from your excluded part of code
int dup = 1; // from your excluded part of code
int leng = strlen(word); // length of input word
int n = leng - dup; // char remained to be inserted
// iterator for new array(newAbc)
int c = n; // n elements are already there
// Just reversed your loop
for (int b = 0; b < 27; b++)
{
int found = 0;
for (int i = 0; i < n; i++)
{
if (newAbc[i] == abc[b])
{
found = 1;
break;
}
}
if (!found)
{
newAbc[c] = abc[b];
c++;
}
}
for (int i = 0; i < 27; i++)
cout << newAbc[i];
cout << endl;
return 0;

String matching algorithm trying to correct it

I'm trying to do string matching algorithm a brute force method. but The algorithm is not working correctly, I get an out of bound index error.
here is my algorithm
int main() {
string s = "NOBODY_NOTICED_HIM";
string pattern="NOT";
int index = 0;
for (int i = 0; i < s.size();)
{
for (int j = 0; j < pattern.size();)
{
if(s[index] == pattern[j])
{
j++;
i++;
}
else
{
index = i;
j = 0;
}
}
}
cout<<index<<endl;
return 0;
}
FIXED VERSION
I fixed the out of bound exception. I don't know if the algorithm will work with different strings
int main() {
string s = "NOBODY_NOTICED_HIM";
string pattern="NOT";
int index = 0;
int i = 0;
while( i < s.size())
{
i++;
for (int j = 0; j < pattern.size();)
{
if(s[index] == pattern[j])
{
index++;
j++;
cout<<"i is " <<i << " j is "<<j <<endl;
}
else
{
index = i;
break;
}
}
}
cout<<i<<endl;
return 0;
}
Because the inner for loop has a condition to loop while j is less than pattern.size() but you are also incrementing i inside the body. When i goes out of bounds of s.size() then index also goes out of bounds and you'd get an OutOfBounds error.
The brute force method has to test the pattern with every possible subsequence. The main condition is the length, which has to be the same. All subsequence from s are:
['NOB', 'OBO', 'BOD', 'ODY', 'DY_', 'Y_N', 'NO', 'NOT', 'OTI', 'TIC',
'ICE', 'CED', 'ED', 'D_H', '_HI', 'HIM']
There are many ways to do it, you can do it char by char, or by using string operations like taking a substring. Both are nice excercises for learning.
Starting at zero in the s string you take the first three chars, compare to the pattern, and if equal you give the answer. Otherwise you move on to the char starting at one, etc.

c++: string.replace inserting too many characters

I'm trying to step through a given string with a for loop, replacing one character per iteration with a character from a vector[char].
Problem is that the replace inserts the entire vector-k instead of the character at place k and I cannot figure out what I've done wrong.
Any and all help is appreciated.
(alphabet is a const string a-z, FirstWord is the given string).
vector<char> VectorAlphabet;
for (int i=0; i<alphabet.length(); ++i)
{
VectorAlphabet.push_back(alphabet.at(i));
}
for (int i = 0; i < FirstWord.length(); ++i )
{
for (int k = 0; k < VectorAlphabet.size(); ++k)
{
string TempWord = FirstWord;
TempWord.replace(i, 1, &VectorAlphabet[k]);
if (CheckForValidWord(TempWord, WordSet))
{
if(CheckForDuplicateChain(TempWord, DuplicateWordSet))
{
DuplicateWordSet.insert(TempWord);
stack<string> TempStack = WordStack;
TempStack.push(TempWord);
WordQueue.push(TempStack);
}
}
}
}
e.g TempWord = tempword, then after TempWord.replace() on the first iteration it is abcde...zempWord. and not aempword. On the second to last iteration of the second for loop it is yzempword.
What have I missed?
Problem solved, thanks to Dieter Lücking.
Looking closer at the string.replace reference, I see that I tried to use a replace which takes strings as the input, and then the vector[char] is interpreted as a c-string, starting from the k-position.
By using the fill-version of replace the vector position is correctly used as a char instead.
New code is:
for (int i = 0; i < FirstWord.length(); ++i )
{
for (int k = 0; k < VectorAlphabet.size(); ++k)
{
string TempWord = WordStack.top();
// Change:
TempWord.replace(i, 1, 1, VectorAlphabet[k]);
if (CheckForValidWord(TempWord, WordSet))
{
if(CheckForDuplicateChain(TempWord, DuplicateWordSet))
{
DuplicateWordSet.insert(TempWord);
stack<string> TempStack = WordStack;
TempStack.push(TempWord);
WordQueue.push(TempStack);
}
}
}
}