im trying to read a large file, so i thought that instead of looping with an array i decided to use a list, but I'm having some difficulties with searching a line which contains a word that needs to be searched for. Here is my code
public List<string> AWfile = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
if (File.Exists(#"C:\DataFolder\file.txt"))
{
using (StreamReader r = new StreamReader(#"C:\DataFolder\file.txt"))
{
string line;
while ((line = r.ReadLine()) != null)
{
AWfile.Add(line); label1.Text = "ListWritten!"; label1.BackColor = Color.Green;
}
}
}
}
private void button2_Click(object sender, EventArgs e)
{
int linen = AWfile.IndexOf("A102");
label2.Text = Convert.ToString(linen);
}
So my question is if there is any way to search just for a part of a word in a list instead of the whole string, because that's the only way the .IndexOf returns me anything at all.
You can try something like:
var result = list.Select(x => x.Contains("hello")).ToList()
This will result in a list with all the elements in the list which contains "hello".
And if you want to do something only with this elements:
list.Select(x => x.Contains("hello")).ToList().ForEach(x => DoSomething(x));
I hope this helps
If I understand your question correctly... you are reading in a file and adding each line to a list. Then you want to check if any of those lines contain part of a word.
One way of doing this would be to do a foreach loop over each of the lines in your list and checking if the line contains the partial word.
Something like:
foreach(var line in AWFile)
{
if(line.Contains("PartialWordWeWant"))
{
// Do something with the line that contains the word we are looking for
}
}
Related
I have the following code. Dictionary is just a wrapper for a List of type String.
public Dictionary getDictionary(int size, String text) {
return restTemplate.execute(url, HttpMethod.GET, null, response -> {
BufferedReader br = new BufferedReader(new InputStreamReader(response.getBody()));
List<String> words = new ArrayList<>();
String line;
while((line = br.readLine()) != null){
if (isMatch(line, size, text)){
words.add(line.toLowerCase());
}
}
br.close();
return new Dictionary(words);
});
}
private boolean isMatch(String word, int size, String text) {
if(word.length() != size) {
return false;
}
return wordUtil.isAnagram(word, text);
}
I'm having a hard time test this method at the moment. The HTTP call just returns a list of words in plain text with new line separators.
I want to write a test where I can stub the response.getBody().
I.e. I want response.getBody() to return a bunch of words, and I'll assert that the returned Dictionary only contains the words that are of size size and that are an anagram of the string text.
Is this possible?
Thanks
It is possible to stub a method taking a callback, and execute the callback when the stub is called.
The idea is to:
use when / thenAnswer to execute code when the stubbed method is called
use invocationOnMock passed to thenAnswer to get the callback instance
call the callback, providing necessary params
#Test
void testExecute() {
String responseBody = "line1\nline2";
InputStream responseBodyStream = new ByteArrayInputStream(responseBody.getBytes());
ClientHttpResponse httpResponse = new MockClientHttpResponse(responseBodyStream, 200);
when(restTemplate.execute(any(URI.class), eq(HttpMethod.GET), eq(null), any())).thenAnswer(
invocationOnMock -> {
ResponseExtractor<MyDictionary> responseExtractor = invocationOnMock.getArgument(3);
return responseExtractor.extractData(httpResponse);
}
);
MyDictionary ret = aController.getDictionary(1, "text");
// assert ret against your expecations
}
Having said that, this seems to be a bit complicated for the task at hand. IMHO you will be better off if you separate the logic of dealing with Http from your business logic. Extract a method taking your inputStream, and test that separately.
I am trying to find if a any element of a first list is found for each line of a csv file
First list :
XX01235756777
YY01215970799
Second list (that would be the csv file) :
Column_1|Column_2|Column_3|Column_4|Column_5|Column_6|Column_7
VX|2022-06-09 11:50:55|Y|Y|N|TT56431254135|Microsoft
VX|2022-06-09 11:50:55|Y|Y|N|XX01235756777|Meta
VX|2022-06-09 11:50:55|Y|Y|N|YY18694654355|Nokia
VX|2022-06-09 11:50:55|Y|Y|N|OO01215970799|BlackStone
VX|2022-06-09 11:50:55|Y|Y|N|YY01215970799|Alphabet
My code attempt :
List<string> filteredList = new List<string>();
using (StreamReader reader = new StreamReader(csvFilePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (line.Any(x => isinList.Contains(x.ToString())))
{
filteredList.Add(line);
}
}
}
return filteredList;
filteredList should be :
VX|2022-06-09 11:50:55|Y|Y|N|XX01235756777|Meta
VX|2022-06-09 11:50:55|Y|Y|N|YY01215970799|Alphabet
I succeeded at finding a single element in each line of the csv file.
But I can't code the right LINQ to process if whole list is present in each line.
Any ideas or anywhere you can point me to would be a great help.
What you have ends up splitting the line from the csv file into characters and each character is checked against the isinList. You should instead check if any string in the isinList exists in each line from the csv file.
List<string> filteredList = new List<string>();
using (StreamReader reader = new StreamReader(csvFilePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
if (isinList.Any(x => line.Contains(x)))
{
filteredList.Add(line);
}
}
}
Using LINQ, and the File.ReadLines() to read the lines in the file, you can filter as follows:
var filteredLines = File.ReadLines(csvFilePath)
.Where(line => isinList.Any(isin => line.Contains(isin)))
.ToList();
OTOH, if isinList is very large, or the CSV file is very long, and you know Column_6 is the only possible match, you might gain performance by using a HashSet<string> and testing only Column_6:
var isinSet = isinList.ToHashSet();
var filteredLines = File.ReadLines(csvFilePath)
.Where(line => isinSet.Contains(line.Split('|')[5]))
.ToList();
class Article{
final String id;
final List<ArticleArray> arrays;
}
class ArticleArray {
final String id;
final String array;
}
TextFormField(
onChanged: (_searchinput) {
List<String> searcharray = _searchinput.split(',');
),
_articlesForDisplay = _articles.where((article){
for(int i = 0; i < article.arrays.length; i++)
{
searchinit = article.arrays[i].arrays.toLowerCase();
}
return searchinit.contains(
RegExp(//necessary code here, caseSensitive: false),
);})
basically what i am trying to do is i am trying to search
array by array like:
-Textformfields follows the user input and every time "," is entered,i
put that word into "searcharray".
-Then i initiate a search in my function(total code is not needed to write here,
i included necessary functions),i try to use "regexp" function to search for the arrays
in my article archives.
Example:
articles[0].arrays[0].array = 'a1'
articles[0].arrays[1].array = 'a2'
articles[1].arrays[0].array = 'a1'
articles[1].arrays[1].array = 'b2'
searcharray = ['a1','b2']
Here,basically what i try to do is i try to search my article arrays by every list of arrays as possible so it matches the right one. Thats what i want.
Not sure I understand your specific requirements.
Here, I define a RegExp that I try to match to at least one item of my data.
void main() {
List<String> data = ['a1','b2', 'c3', 'a4', 'a5', 'd6'];
RegExp exp = new RegExp(r"(a\d+)");
print(data.any((item) => exp.hasMatch(item)));
}
I am trying to prevent name duplicates in a List, but with no luck so far.I have a list of entries and each entry has a name (e.g. entries: "file", "file1", "someFile", "anotherFile"). Whenever I create new entry I add it to the entry List. But I don't want to add new entry with the same name.I have a file that I just created (e.g. name: "file"). How do I find all name duplicates and make it something like this at the end: "file2"?
Sorry if the question is a bit vague.
I tried to use LINQ and Regex, but I'm kind of new to those things so not sure what I'm doing..
According to what you have posted in question a simple program with if-else conditions could solve your problem:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
string[] entries = new []{"file", "file1", "someFile", "anotherFile", "file", "someFile", "file"};
List<string> curatedEntries = new List<string>();
foreach(string e in entries)
{
int index = 0;
string entry = e;
Check:
if(CheckExists(curatedEntries, entry)){
index++;
entry = e + index;
goto Check;
}
curatedEntries.Add(entry);
}
curatedEntries.ForEach(x=>Console.WriteLine(x));
}
public static bool CheckExists(List<string> lst,string e)
{
return lst.Any(x=>x.Equals(e));
}
}
Here's fiddle: https://dotnetfiddle.net/fdSClH
I recently started learning Groovy.
I have a small task: get all lowercase words from string as List
I wrote next code:
public List<String> findWordsInLowercase(String string){
return string.findAll(/\b[a-z]+\b/)
}
It work. But i want to do it without regex, because it's very difficult to read, understand and remember.
Now i try to write same function without regex. My code:
public List<String> findWordsInLowercase(String string){
def words = string.split()
words.findAll
{it -> for(Character character in it)
character.isLowerCase()}
}
But it doesn't work :(
Rather than checking every character, why not check the word is the same as it's lowercase representation?
public List<String> findWordsInLowercase(String string) {
def words = string.split()
words.findAll { word ->
word.toLowerCase() == word
}
}
Or, it might be more understandable to make your first function:
public List<String> findWordsInLowercase(String string) {
string.findAll( /\b\p{javaLowerCase}+\b/ )
}
Which should improve readability, and you don't need to remember it, as you now have a function ;-)
You can also use meta programming to extend String class and then use this extension in normal method:
String.metaClass.isLowerCase = {
delegate ? delegate.every { it.toCharacter().isLowerCase() } : false
}
public List<String> findWordsInLowercase(String string){
string.split().findAll { it.isLowerCase() }
}
assert findWordsInLowercase('AAA bbb') == ['bbb']