I have a question regarding C#, strings and arrays.
I've searched for similar questions at stack overflow, but could not find any answers.
My problem:
I have a string array, which contains words / wordparts to check file names. If all of these strings in the array matches, the word is "good".
String[] StringArray = new String[] { "wordpart1", "wordpart2", ".txt" };
Now I want to check if all these strings are a part of a filename. If this checkresult is true, I want to do something with this file.
How can I do that?
I already tried different approaches, but all doesn't work.
i.e.
e.Name.Contains(StringArray)
etc.
I want to avoid to use a loop (for, foreach) to check all wordparts. Is this possible?
Thanks in advance for any help.
Now I want to check if all these strings are a part of a filename. If this checkresult is true, I want to do something with this file. How can I do that?
Thanks to LINQ and method groups conversions, it can be easily done like this:
bool check = StringArray.All(yourFileName.Contains);
Similar question: Using C# to check if string contains a string in string array
This uses LINQ:
if(stringArray.Any(stringToCheck.Contains))
This checks if stringToCheck contains any one of substrings from
stringArray. If you want to ensure that it contains all the
substrings, change Any to All:
if(stringArray.All(s => stringToCheck.Contains(s)))
Related
Im making an app which needs to loop through steam games.
reading libraryfolder.vbf, i need to loop through and find the first value and save it as a string.
"libraryfolders"
{
"0"
{
"path" "D:\\Steam"
"label" ""
"contentid" "-1387328137801257092942"
"totalsize" "0"
"update_clean_bytes_tally" "42563526469"
"time_last_update_corruption" "1663765126"
"apps"
{
"730" "31892201109"
"4560" "9665045969"
"9200" "22815860246"
"11020" "776953234"
"34010" "11967809445"
"34270" "1583765638"
for example, it would record:
730
4560
9200
11020
34010
34270
Im already using System.Text.JSON in the program, is there any way i could loop through and just get the first value using System.Text.JSON or would i need to do something different as vdf doesnt separate the values with colons or commas?
That is not JSON, that is the KeyValues format developed by Valve. You can read more about the format here:
https://developer.valvesoftware.com/wiki/KeyValues
There are existing stackoverflow questions regarding converting a VDF file to JSON, and they mention libraries already developed to help read VDF which can help you out.
VDF to JSON in C#
If you want a very quick and dirty way to read the file without needing any external library I would probably use REGEX and do something like this:
string pattern = "\"apps\"\\s+{\\s+(\"(\\d+)\"\\s+\"\\d+\"\\s+)+\\s+}";
string libraryPath = #"C:\Program Files (x86)\Steam\steamapps\libraryfolders.vdf";
string input = File.ReadAllText(libraryPath);
List<string> indexes = Regex.Matches(input, pattern, RegexOptions.Singleline)
.Cast<Match>().ToList()
.Select(m => m.Groups[2].Captures).ToList()
.SelectMany(c => c.Cast<Capture>())
.Select(c => c.Value).ToList();
foreach(string s in indexes)
{
Debug.WriteLine(s);
}
See the regular expression explaination here:
https://regex101.com/r/bQSt79/1
It basically captures all occurances of "apps" { } in the 0 group, and does a repeating capture of pairs of numbers inbetween the curely brackets in the 1 group, but also captures the left most number in the pair of numbers in the 2 group. Generally repeating captures will only keep the last occurance but because this is C# we can still access the values.
The rest of the code takes each match, the 2nd group of each match, the captures of each group, and the values of those captures, and puts them in a list of strings. Then a foreach will print the value of those strings to log.
I have a string as shown below
string names = "<?startname; Max?><?startname; Alex?><?startname; Rudy?>";
is there any way I can split this string and add Max , Alex and Rudy into a separate list ?
Sure, split on two strings (all that consistently comes before, and all that consistently comes after) and specify that you want Split to remove the empties:
var r = names.Split(new[]{ "<?startname; ", "?>" }, StringSplitOptions.RemoveEmptyEntries);
If you take out the RemoveEmptyEntries it will give you a more clear idea of how the splitting is working, but in essence without it you'd get your names interspersed with array entries that are empty strings because split found a delimiter (the <?...) immediately following another (the ?>) with an empty string between the delimiters
You can read the volumes of info about this form of split here - that's a direct link to netcore3.1, you can change your version in the table of contents - this variant of Split has been available since framework2.0
You did also say "add to a separate list" - didn't see any code for that so I guess you will either be happy to proceed with r here being "a separate list" (an array actually, but probably adequately equivalent and easy to convert with LINQ's ToList() if not) or if you have another list of names (that really is a List<string>) then you can thatList.AddRange(r) it
Another Idea is to use Regex
The following regex should work :
(?<=; )(.*?)(?=\s*\?>)
What would be the fastest way to check if a string contains any matches in a string array in C#? I can do it using a loop, but I think that would be too slow.
Using LINQ:
return array.Any(s => s.Equals(myString))
Granted, you might want to take culture and case into account, but that's the general idea.
Also, if equality is not what you meant by "matches", you can always you the function you need to use for "match".
I really couldn't tell you if this is absolutely the fastest way, but one of the ways I have commonly done this is:
This will check if the string contains any of the strings from the array:
string[] myStrings = { "a", "b", "c" };
string checkThis = "abc";
if (myStrings.Any(checkThis.Contains))
{
MessageBox.Show("checkThis contains a string from string array myStrings.");
}
To check if the string contains all the strings (elements) of the array, simply change myStrings.Any in the if statement to myStrings.All.
I don't know what kind of application this is, but I often need to use:
if (myStrings.Any(checkThis.ToLowerInvariant().Contains))
So if you are checking to see user input, it won't matter, whether the user enters the string in CAPITAL letters, this could easily be reversed using ToLowerInvariant().
Hope this helped!
That works fine for me:
string[] characters = new string[] { ".", ",", "'" };
bool contains = characters.Any(c => word.Contains(c));
You could combine the strings with regex or statements, and then "do it in one pass," but technically the regex would still performing a loop internally. Ultimately, looping is necessary.
If the "array" will never change (or change only infrequently), and you'll have many input strings that you're testing against it, then you could build a HashSet<string> from the array. HashSet<T>.Contains is an O(1) operation, as opposed to a loop which is O(N).
But it would take some (small) amount of time to build the HashSet. If the array will change frequently, then a loop is the only realistic way to do it.
I will have always an string like this:
"/FirstWord/ImportantWord/ThirdWord"
How can I extract the ImportantWord? Words can contain at most one space and they are separated by forward slashlike I put above, for example:
"/Folder/Second Folder/Content"
"/Main folder/Important/Other Content"
I always want to get the second word(Second Folder and Important considering above examples)
how about this:
string ImportantWord = path.Split('/')[2]; // Index 2 will give the required word
I hope you need not to use the String.Split option either with specific characters or with some regular expressions. Since the inputs are well qualified paths to a directory you can use Directory.GetParent method of the System.IO.Directory class, which will give you the parent Directory as DirectoryInfo. From that you can take the Name of Directory which will be the required text.
You can use like this :
string pathFirst = "/Folder/Second Folder/Content";
string pathSecond = "/Main folder/Important/Other Content";
string reqWord1 = Directory.GetParent(pathFirst ).Name; // will give you Second Folder
string reqWord2 = Directory.GetParent(pathSecond).Name; // will give you Important
Additional note: The method Directory.GetParent can be nested if you need to get a name in another level.
Also you may try this:
var stringValue = "/FirstWord/ImportantWord/ThirdWord";
var item = stringValue.Split('/').Skip(2).First(); //item: ImportantWord
There are several ways to solve this. The simplest one is using String.split
Char delimiter = '/';
String[] substrings = value.Split(delimiter);
String secondWord = substrings[1];
(you may want to do some input check to make sure the input is in the right format or else you will get some exception)
Other way is using regex when the pattern is simple /
If you are sure this is a path you can use other answer mention here
How can i store the contents of a string variable to a text file ?
How can i search in a string variable for specific text for example find if the word book is in the string?
To save the file to text you can do:
System.IO.File.WriteAllText("C:\your_path\your_file", Your_contents);
To Search for something in the string:
var position = Your_string.IndexOf("Book");
If position equals -1 then what you are searching for isn't there.
In the off chance you are actually stumped on where to find this information, it's as simple as:
System.IO.File.WriteAllText(myPathToTheFile, myStringToWrite);
To find a string within another string, you would simply do this:
myString.Contains(someOtherString); // boolean
myString.IndexOf(someOtherString); // find the 0 based index of the target string
File.WriteAllText("MyFile.txt", myString); // Write all string to file
var wordBookIndex = myString.IndexOf("book"); // If the string is found, index != -1
System.IO namespace has various methods and classes for file (and other) IO, this one may serve your purpose easily:
http://msdn.microsoft.com/en-us/library/system.io.file.writealltext.aspx
As for searching inside a single string, use String.IndexOf:
http://msdn.microsoft.com/en-us/library/system.string.indexof.aspx
answer to 1 question
make use of System.IO namespace in that there are not class availabe to wirte the text in file
answer to 2 question
you can use Regular expression or make use of IndexOf function to serach specific word in string