givenC:
public void testByRow1() {
List<List<String>> grid = new ArrayList<List<String>>();
grid.add(new ArrayList<String>());
grid.get(0).add("hello ");
grid.get(0).add("there!");
grid.add(new ArrayList<String>());
grid.get(1).add(null);
grid.get(1).add(" How's it going?");
String gotBack = Drill05.byRow(grid);
String expected = "hello there! How's it going?";
System.out.println(
"byRow: expected = " + expected + ", gotBack = " + gotBack);
assertEquals(expected, gotBack);
}
myC:
public static String byRow(List<List> grid) {
String sentence;
String ans = "";
String pull ="null";
//Nested for loop goes through the grid and
for(int i =0; i <= 1; i++)
for(int j = 0; j<= 1; j++) {
sentence = grid.get(i).get(j);
sentence = sentence + " ";
//this takes the String sentence and removes
//null and puts in it's place a " " string
if(sentence.contains(pull)) {
ans = sentence.replace(pull, " ");
return ans;
}else
return ans;
}
return ans;
}
Hello I am new to this whole data structure coding stuff and my problem is that I have to go through a list of list grid and make a sentence of the elements. Once that sentence has been made, I have to replace "null" with a " " empty string. The above code for givenC and myC works when it is all in the same method together but when I put the code into the respective separate methods, the code no longer works. There are three return statements in the Myclass because that was the brute force way of how my IDE was telling me to fix my errors. I been working all day on trying to figure this out and had no luck at all. I have to submit this in a few hours and I can't find anything online or in class lectures similar to the problem I'm having that works. Please help me understand what to do to fix this bug and why its occurring!
Related
So I'm stuck at a point in my code. I need to make a function that can be used to find instances of a list of words in a file.
So, for example, I currently have it to where I can type Breaking-Bad, or Lilo-Stitch; these words are then broken to [breaking, bad] [lilo, stitch] in a vector. The issues arise when I use the function on the bottom.
The function works when it comes to the first index; it will find all instances of the words, like [breaking] or [lilo], but it doesn't output anything else for the other indexes. How can I improve on this section of code?
To further explain, the idea of the code is to find all lines in the file that have one to all of the words typed by the user.
int searchfile(fstream& file, vector<string>& UserSearch, int counter)
{
string input;
int amount = 0;
int line = 0;
for (int i = 0; i < counter; i++) {
while (getline(file, input))
{
line++;
if (input.find(UserSearch[i], 0) != string::npos)
{
cout << "found " << UserSearch[i] << " in line " << line << endl;
amount++;
}
}
}
return amount;
}
I already tried using a for loop in main but it gave the same results.
for (int i = 0; i < list.size; i++) {
searchFile(infile, list, counter);
}
I need a code that splits string texts like:
string part1 = "Hi i study computer science in a college";
Then, I want it to be added into my linked list.
Node1: "Hi"
Node2: "i"
Node3: "study"
Node4: "computer"
...
I took a look but I couldn't find any source to do it. So can anyone help me?
Sure, let me do your homework:
using It = std::istream_iterator<std::string>;
std::list<std::string> list(It(std::istringstream(part1) >> std::ws), It());
std::for_each(begin(list), end(list),
[i=0](auto const& s) mutable { std::cout << “Node” << ++i << “\n”; });
Inconveniently it uses too much magic to be an acceptable solution to your teacher.
I tried it myself with a complicated algorithm. here's the code
string metin[500];
string a;
getline(cin,a);
int pos = 0;
string str1;
int elemans = 0;
for (int i = 0;i<=a.length();i++)
{
if(a[i] == ' '|| i == a.length())
{
for(int j=pos; j<i;j++)
{
str1 = str1 + a[pos];
pos++;
}
pos = i+1;
metin[elemans] = str1;
elemans++;
str1 = "";
}
}
cout << str1;
cout << a.length() << endl;
for(int i = 0; i<elemans;i++)
{
cout << metin[i] << endl;
}
It's string split..
you can add for loop and addnode(metin[i]) you can do it yourselves.
If this is for homework, please do the exercise. If you skip the simple stuff you will never learn.
However, if you are genuinely interested in learning more, it is helpful to know that this kind of operation is known as "tokenizing". Google it. You may find more information than you can understand, but it will improve your knowledge of the theories.
A good discussion of it can be found here How do I tokenize a string in C++?
I am trying to understand why my iterator code will not print the correct statement even though I am passing the correct variable through to it. I am still new to C++ and have figured that this is probably an easy fix but could anyone help ??
Ps - it works fine when I have already declared an input but when I wish for the code to accept user input it gives inaccurate results
int main(){
list<string> personWords = {"Baxter","Nao","Jane"};
list <string> actionWords ={"recognise","detect","sees","pick","eats","lifts"};
list <string> directionWords = {"left","right","forwards","backwards"};
list <string> pronounWords = {"I","you","him","her"};
list <string> objectWords = {"apple","car","bus","diamond","atom","ball"};
list <string> textureWords = {"smooth","rough","shiny"};
string userInput;
cin >> userInput;
string userInputWords[3];
int counter = 0;
for(int i = 0; i <= userInput.length(); i++){
if (userInput[i] == ' '){
counter++;}
else{
userInputWords[counter] += userInput[i];
}
}
// The above for loop counts the number of words using the
// number of spaces inbetween the words and stores them in an
// array
cout << userInputWords[0] << endl; // A check to see that correct word is being printed
list <string> ::iterator check1;
check1 = find(personWords.begin(), personWords.end(), userInputWords[0]);
// searching for all of the person words
if(check1 != personWords.end()){
cout << "Your word exists in Person Words list" << endl;
}
else{
cout << "Your word does not exist in Person Words list" << endl;
}
}
this is probably an easy fix
for(int i = 0; i <= userInput.length(); i++)
^^
It should just be
for (int i = 0; i < userInput.length(); i++)
When it is less than or equals, it adds all the characters the user typed plus one.
That's why std::find couldn't find what you were typing, because it was also grabbing whatever was right after the word (probably a \0, but don't quote me on that.)
I have prompted the user to input a string in the main function in my program and store it userString, and want to display how many words there are.
This is the function I intend to call from main:
int countWords(string d) {
string words = " ";
for (int e = 0; e < d.length(); e++) {
if (isspace(d[e])) {
cout << "The string " << words << "word(s). ";
}
}
return words;
}
I read somewhere that the function should actually count the number of white spaces (which is why I used isspace()), and not the words themselves.
How do I go about counting the number of words there are in the string and displaying it in the same function? I am having trouble figuring it out and I'm getting errors.
I also cannot use library functions.
Expected output:
The string "2020" has one word.
The string "Hello guys" has two words.
If you don't want to use boost, a simple for loop will do.
#include <cctype>
...
for(int i = 0; i < toParse.length(); i++){
if (isblank(toParse[i])){
//start new word
}
else if (toParse[i] == '.'){
//start new sentence
}
else if (isalphanum(toParse[i])){
//add to your current word
}
}
edit: you can just increment an integer where you see the //start new word.
try boost::split(), which will put words into a vector
Also, if you want to count something in a range satisfying some condition, you can think in std::count_if
Example:
int countWords(std::string d)
{
int w = std::count_if(d.begin(), d.end(), [](char ch) { return isspace(ch); });
std::cout << "The string \"" << d << "\" has " << w + 1 << " words." << '\n';
return w;
}
Here is the assignment:
Write a program that reads in a text file one word at a time. Store a word into a dynamically created array when it is first encountered. Create a paralle integer array to hold a count of the number of times that each particular word appears in the text file. If the word appears in the text file multiple times, do not add it into your dynamic array, but make sure to increment the corresponding word frequency counter in the parallel integer array. Remove any trailing punctuation from all words before doing any comparisons.
Create and use the following text file containing a quote from Bill Cosby to test your program.
I don't know the key to success, but the key to failure is trying to please everybody.
At the end of your program, generate a report that prints the contents of your two arrays in a format similar to the following:
Word Frequency Analysis
I 1
don't 1
know 1
the 2
key 2
...
Here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int readInFile (string tempArray [], string file, int arraySize);
int main()
{
ifstream inputFile;
string *readInArray = 0,
*compareArray = 0,
filename,
word;
int wordCount = 0;
int encountered = 0;
int j = 0,
*wordFrequency = 0;
cout << "Enter the filename you wish to read in: ";
getline(cin, filename);
inputFile.open(filename.c_str());
if (inputFile)
{
while (inputFile >> word)
{
wordCount++;
}
inputFile.close();
readInArray = new string[wordCount];
readInFile(readInArray, filename, wordCount);
}
else
{
cout << "Could not open file, ending program";
return 0;
}
compareArray = new string[wordCount];
wordFrequency = new int[wordCount];
for (int count = 0; count < wordCount; count++)
wordFrequency[count] = 0;
for(int i = 0; i < wordCount; ++i)
{
j = 0;
encountered = 0;
do
{
if (readInArray[i] == compareArray[j])
encountered = 1;
++j;
} while (j < wordCount);
if (encountered == 0)
{
compareArray[i]=readInArray[i];
wordFrequency[i] += 1;
}
}
for(int k=0; k < wordCount; ++k)
{
cout << "\n" << compareArray[k] << " ";
}
for(int l=0; l < wordCount; ++l)
{
cout << "\n" << wordFrequency[l] << " ";
}
return 0;
}
int readInFile (string tempArray [], string file, int arraySize)
{
ifstream inputFile;
inputFile.open(file.c_str());
if (inputFile)
{
cout << "\nHere is the text file:\n\n";
for(int i=0; i < arraySize; ++i)
{
inputFile >> tempArray[i];
cout << tempArray[i] << " ";
}
inputFile.close();
}
}
Here is my question:
How do you store a word into a dynamically created array when it is first encountered? As you can see from my code made a string array with some of the elements empty. I believe it is suppose to be done using pointers.
Also how do I get rid of the punctuation in the string array? Should it be converted to a c-string first? But then how would I compare the words without converting back to a string array?
Here is a link to a java program that does something similar:
http://math.hws.edu/eck/cs124/javanotes3/c10/ex-10-1-answer.html
Thank you for any help you can offer!!
As to the first part of your question, you are not using a dynamically created array. You are using a regular array. C++ provides implementations of dymnamic arrays, like the vector class http://www.cplusplus.com/reference/vector/vector/
As to the second part of your question, I see no reason to convert it to a c string. The string class in c++ provides functionality for removing and searching for characters. http://www.cplusplus.com/reference/string/string/
The string::erase function can be used to erase punctuation characters found with string::find.
Note: There are other ways of doing this assignment that may be easier (like having an array of structs containing a string and an int, or using a map) but that may defeat the purpose of the assignment.