I want to search a particular word in a defined string for which I am using the foreach key word, but it's not working.
I am just a beginner at this. Please help me what is wrong in this and I don't want to use arrays.
static void Main(string[] args)
{
string str = "Hello You are welcome";
foreach (string item in str) // can we use string here?
{
if (str.Contains(are); // I am checking if the word "are" is present in the above string
Console.WriteLine("True");
)
}
string str = "Hello You are welcome";
if (str.Contains("are"))
{
Console.WriteLine("True");
}
or you mean:
string str = "Hello You are welcome";
foreach (var word in str.Split()) // split the string (by space)
{
if (word == "are")
{
Console.WriteLine("True");
}
}
Try this
static void Main(string[] args)
{
string str = "Hello You are welcome";
foreach (var item in str.Split(' ')) // split the string (by space)
{
if (item == "are")
{
Console.WriteLine("True");
}
}
}
Related
I wrote a exam last week and had a really hard task to solve and didn't got the point.
I had a .txt with a Text.
The Text is like this:
Der zerbrochne Krug, ein Lustspiel,
von Heinrich von Kleist.
Berlin. In der Realschulbuchhandlung.
1811.
[8]
PERSONEN.
WALTER, Gerichtsrath. ADAM, Dorfrichter. LICHT, Schreiber. FRAU MARTHE
RULL. EVE, ihre Tochter. VEIT TÜMPEL, ein Bauer. RUPRECHT, sein Sohn.
FRAU BRIGITTE. EIN BEDIENTER, BÜTTEL, MÄGDE, etc.
Die Handlung spielt in einem niederländischen Dorfe bei Utrecht.
[9] Scene: Die Gerichtsstube. Erster Auftritt.
And i got the Main with this code:
var document = new Document("Text.txt");
if (document.Contains("Haus") == true)
Console.WriteLine(document["Haus"]); // Word: haus, Frequency.: 36, Length: 4
else
Console.WriteLine("Word not found!");
Now i had to write a class which helps to make the code above works.
Does anyone have an idea how to solve this problem and would help a young student of business informatics to understand, how this works?
Normally the StreamReader is easy for me, but in this case it wasn't possible for me...
Thank you very much and much love and healthy for all of you, who tries tohelpme.
Well this is the class you are looking for, hope this might help you.
class Document : Dictionary<string, int>
{
private const char WORDSPLITTER = ' ';
public string Filename { get; }
public Document(string filename)
{
Filename = filename;
Fill();
}
private void Fill()
{
foreach (var item in File.ReadLines(Filename))
{
foreach (var word in item.Split(WORDSPLITTER))
{
if (ContainsKey(word))
base[word] += 1;
else
Add(word, 1);
}
}
}
public bool Contains(string word) => ContainsKey(word);
public new string this[string word]
{
get
{
if (ContainsKey(word))
return $"Word: {word}, frequency: {base[word]}, Length: {word.Length}";
else
return $"Word {word} not found!";
}
}
}
Try the below function :
private bool FindWord( string SearchWord)
{
List<string> LstWords = new List<string>();
string[] Lines = File.ReadAllLines("Path of your File");
foreach (string line in Lines )
{
string[] words = line.Split(' ');
foreach (string word in words )
{
LstWords.Add(word);
}
}
// Find word set word to upper letters and target word to upper
int index = LstWords.FindIndex(x => x.Trim ().ToUpper ().Equals(SearchWord.ToUpper ()));
if (index==-1)
{
// Not Found
return false;
}
else
{
//word found
return true;
}
}
I find that Regex could be a good way to solve this:
var ms = Regex.Matches(textToSearch, wordToFind, RegexOptions.IgnoreCase);
if (ms.Count > 0)
{
Console.WriteLine($"Word: {wordToFind} Frequency: {ms.Count} Length: {wordToFind.Length}");
}
else
{
Console.WriteLine("Word not found!");
}
Regex is in the namespace:
using System.Text.RegularExpressions;
You will need to set the RegexOptions that are appropriate for your problem.
One of the approach would be below steps-
Create a class Document with below properties -
//Contains file name
public string FileName { get; set; }
//Contains file data
public string FileData { get; set; }
//Contains word count
public int WordCount { get; set; }
//Holds all the words
public Dictionary<string, int> DictWords { get; set; } = new Dictionary<string, int>();
Define the constructor which does 2 things -
Assign the property Filename to incoming file
Read the file from the path and get all the words from the file
Find the word count and insert them to dictionary, so the Final dictionary will
have all the <<<'word'>>, <<'TotalCount'>>> records
//Constructor
public Document(string fileName)
{
//1/ Assign File Name name troperty
FileName = fileName;
//2. Read File from the Path
string text = System.IO.File.ReadAllText(fileName, Encoding.Default);
string[] source = text.Split(new char[] { '.', '!', '?', ',', '(', ')', '\t', '\n', '\r', ' ' },
StringSplitOptions.RemoveEmptyEntries);
//3. Add the counts to Dictionary
foreach (String word in source)
{
if (DictWords.ContainsKey(word))
{
DictWords[word]++;
} else
{
DictWords[word] = 1;
}
}
}
Create "Contains" method which will be used to check whether the word is present or
not in the document-
//4. Method will return true /false based on the existence of the key/word.
public bool Contains(string word)
{
if (DictWords.ContainsKey(word))
{
return true;
}
else
{
return false;
}
}
Create an indexer on string for the class to get the desired output to be print to
Console -
//4. Define index on the word.
public string this[string word]
{
get
{
if (DictWords.TryGetValue(word, out int value))
{
return $"Word: {word}, Frequency.:{value}, Length: {word.Length}";
}
return string.Empty;
}
}
Tests :
var document = new Document(#"Text.txt");
if (document.Contains("BEDIENTER") == true)
Console.WriteLine(document["BEDIENTER"]);
else
Console.WriteLine("Word not found!");
//Output
// Word: BEDIENTER, Frequency.:1, Length: 9
I have some sql commands that are separated by an additional newline character:
ALTER TABLE XXX
ALTER COLUMN xxx real
ALTER TABLE YYY
ALTER COLUMN yyy real
ALTER TABLE ZZZ
ALTER COLUMN zzz real
I've tried reading the file by using an array of character separators such as the following,
new char[] { '\n', '\r'}
inside this method:
private static List<string> ReadFile(string FileName, char[] seps)
{
if (!File.Exists(FileName))
{
Console.WriteLine("File not found");
return null;
}
using (StreamReader sr = new StreamReader(FileName, Encoding.Default))
{
string content = sr.ReadToEnd();
return content.Split(seps, StringSplitOptions.RemoveEmptyEntries).ToList();
}
}
However, this doesn't seem to be working. I would like to have each command represented by a separate string. How can I do this?
Why not use File.ReadAllLines()?
private static List<string> ReadFile(string FileName)
{
if (!File.Exists(FileName))
{
Console.WriteLine("File not found");
return null;
}
var lines = File.ReadAllLines(FileName);
return lines.ToList();
}
This will automatically read and split your file by newlines.
If you want to filter out empty lines, do this:
var nonEmpty = ReadFile(path).Where(x => !string.IsNullOrEmpty(x)).ToList();
Side note, I would change your if statement to throw an exception if the file cannot be found.
if (!File.Exists(FileName))
{
throw new FileNotFoundException("Can't find file");
}
You can filter the examples. When I read them in, the empty lines had a length 1 and its char value said 131 for some reason. So I just filtered by length > 1
void Main()
{
var results = ReadFile(#"C:\temp\sql.txt", new char[]{'\n'});
Console.WriteLine(results.Count);
foreach (var result in results)
{
Console.WriteLine(result);
}
}
private static List<string> ReadFile(string FileName, char[] seps)
{
if (!File.Exists(FileName))
{
Console.WriteLine("File not found");
return null;
}
using (StreamReader sr = new StreamReader(FileName, Encoding.Default))
{
string content = sr.ReadToEnd();
return content.Split(seps, StringSplitOptions.RemoveEmptyEntries).Where (c => c.Length > 1).ToList();
}
}
Try This:
private static List<string> ReadFile(string FileName)
{
List<string> commands = new List<string>();
StringBuilder command = new StringBuilder();
if (!File.Exists(FileName))
{
Console.WriteLine("File not found");
return null;
}
foreach (var line in File.ReadLines(FileName))
{
if (!String.IsNullOrEmpty(line))
{
command.Append(line + "\n");
}
else
{
commands.Add(command.ToString());
command.Clear();
}
}
commands.Add(command.ToString());
return commands;
}
If you are sure you'll always have \r\n line endings, you can use:
var commands = content.Split(new []{"\r\n\r\n"}, StringSplitOptions.RemoveEmptyEntries);
Otherwise, try using regex:
var commands = Regex.Split(content, #"\r?\n\r?\n")
Thank you everyone for your answers. I ended up going with this helper method:
private static List<string> GetCommands(string location)
{
List<string> ret = new List<string>();
List<string> tmp = ReadFile(location, new string[] { "\r\n\r\n"});
for (int i = 0; i < tmp.Count; i++)
{
string rem = tmp[i].Replace("\r", "");
ret.Add(rem);
}
return ret;
}
As an aside, the equivalent is so much easier in Python. For example, what I'm trying to do can be expressed in these three lines:
with open('commands.txt', 'r') as f:
content = f.read()
commands = [ command for command in content.split('\n\n') ]
I've try to parse string like this:
"#1#Process#{some process|info}{some name|some info {child info|child info}}{some name|some info}"
in several messages and create string like this:
#1#Process#
-some process|info
-some name|some info
-child info|child info
-some name|some info
I'm trying to use RegExp and following code:
using System;
using System.Collections;
using System.Text.RegularExpressions;
namespace prRegEXP
{
class Program
{
static String st="";
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// TODO: Implement Functionality Here
var pattern = #"\{(.*?)\}";
var query = "#1#Process#{some process|info}{some name|some info {child info|child info}}{some name|some info}";
FindTree (pattern, query);
Console.WriteLine(st);
Console.WriteLine();
Console.WriteLine("Press any key to continue . . . ");
Console.ReadKey(true);
}
private static void FindTree (String pattern, String query) {
var matches = Regex.Matches(query, pattern);
foreach (Match m in matches) {
st += m.Groups[1] + "\n";
if (Regex.IsMatch(m.Groups[1].ToString(), #"\{(.*?)" )) {
FindTree (#"\{(.*?)", m.Groups[1].ToString());
}
}
}
}
}
It's based on example solution I found and I want to create some message tree which take care about messages inside (like child info|child name). And there can be a lot of them.
I cannot figure out how to match child expressions and send it in recursive parameter. Has any idea or fix?
Writing a simple regex to support N-depth recursions would be impossible(?) or at least very difficult.
A much easier solution would be to just go trough the string char by char and insert indentation and newlines when a new message is found.
Something along the lines of this should work:
private static String FindTree(String query)
System.Text.StringBuilder sb = new System.Text.StringBuilder();
String indent = "";
foreach (var ch in query) {
if (ch == '{') {
sb.Append("\n");
sb.Append(indent);
sb.Append("- ");
indent += "\t";
} else if (ch == '}') {
indent = indent.Substring(1);
} else {
sb.Append(ch);
}
}
return sb.ToString();
}
The above code is not tested, nor am I well versed in C# so it might be full of errors, but it should illustrate the basic idea.
I usually add some strings from a text file into a list or array line by line, although I am now using "#"'s as separators in the text file. How would it be possible to read the two strings "softpedia.com" and "download.com" into a list using the two "#" signs as a breaking point? Baring in mind that there might be more or less strings inbetween the two hashes
e.g.
# Internal Hostnames
softpedia.com
download.com
# External Hostnames
Expected output:
softpedia.com
download.com
class Program
{
static void Main()
{
using (var reader = File.OpenText("test.txt"))
{
foreach (var line in Parse(reader))
{
Console.WriteLine(line);
}
}
}
public static IEnumerable<string> Parse(StreamReader reader)
{
string line;
bool first = false;
while ((line = reader.ReadLine()) != null)
{
if (!line.StartsWith("#"))
{
if (first)
{
yield return line;
}
}
else if (!first)
{
first = true;
}
else
{
yield break;
}
}
}
}
and if you wanted to just get them in a list:
using (var reader = File.OpenText("test.txt"))
{
List<string> hostnames = Parse(reader).ToList();
}
Read it into a buffer and let regex do the work.
string input = #"
# Internal Hostnames
softpedia.com
download.com
# External Hostnames
";
string pattern = #"^(?!#)(?<Text>[^\r\s]+)(?:\s?)";
Regex.Matches(input, pattern, RegexOptions.Multiline)
.OfType<Match>()
.Select (mt => mt.Groups["Text"].Value)
.ToList()
.ForEach( site => Console.WriteLine (site));
/* Outputs
softpedia.com
download.com
*/
It sounds like you want to read all of the lines in between a set of # start lines. If so try the following
List<string> ReadLines(string filePath) {
var list = new List<string>();
var foundStart = false;
foreach (var line in File.ReadAllLines(filePath)) {
if (line.Length > 0 && line[0] == '#') {
if (foundStart) {
return list;
}
foundStart = true;
} else if (foundStart) {
list.Add(line);
}
}
return line;
}
I'm trying to write a simple console app that dumps the contents of HKLM to the console. The output should look something like:
HKEY_LOCAL_MACHINE
HKEY_LOCAL_MACHINE\BCD00000000
HKEY_LOCAL_MACHINE\BCD00000000\Description
KeyName: BCD00000000
System: 1
TreatAsSystem: 1
GuidCache: System.Byte[]
HKEY_LOCAL_MACHINE\BCD00000000\Objects
HKEY_LOCAL_MACHINE\BCD00000000\Objects\{0ce4991b-e6b3-4b16-b23c-5e0d9250e5d9}
HKEY_LOCAL_MACHINE\BCD00000000\Objects\{0ce4991b-e6b3-4b16-b23c-5e0d9250e5d9}\Description
Type: 537919488
HKEY_LOCAL_MACHINE\BCD00000000\Objects\{0ce4991b-e6b3-4b16-b23c-5e0d9250e5d9}\Elements
HKEY_LOCAL_MACHINE\BCD00000000\Objects\{0ce4991b-e6b3-4b16-b23c-5e0d9250e5d9}\Elements\16000020
Element: System.Byte[]
I haven't had much luck researching how to do this. Any help would be greatly appreciated.
You know there's already an app that dumps registry contents, right?
REG EXPORT HKLM hklm.reg
Fun part is, it exports the keys in a text format, but that text file can be imported using either REG or the registry editor.
cHao way is the safiest approach to your question. In the meanwhile, I was bored on this sunday night and wrote something. Just change the Console.WriteLine or add a few other Console.WriteLine to suit your need, whatever need there is.
class Program
{
static void Main(string[] args)
{
Registry.CurrentUser.GetSubKeyNames()
.Select(x => Registry.CurrentUser.OpenSubKey(x))
.Traverse(key =>
{
if (key != null)
{
// You will most likely hit some security exception
return key.GetSubKeyNames().Select(subKey => key.OpenSubKey(subKey));
}
return null;
})
.ForEach(key =>
{
key.GetValueNames()
.ForEach(valueName => Console.WriteLine("{0}\\{1}:{2} ({3})", key, valueName, key.GetValue(valueName), key.GetValueKind(valueName)));
});
Console.ReadLine();
}
}
public static class Extensions
{
public static IEnumerable<T> Traverse<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> fnRecurse)
{
foreach (T item in source)
{
yield return item;
IEnumerable<T> seqRecurse = fnRecurse(item);
if (seqRecurse != null)
{
foreach (T itemRecurse in Traverse(seqRecurse, fnRecurse))
{
yield return itemRecurse;
}
}
}
}
public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var item in source)
{
action(item);
}
}
}
thanks for the answer Pierre-Alain Vigeant, i like ur solution. for the most part it worked with a couple of minor alterations for the text formatting, but i still couldnt deal with the security exception that was being thrown. turns out linq is not so great for this because it does alot of behind the scenes stuff. the following solution is a basic idea of how to do it
class Program
{
static void Main(string[] args)
{
RegistryKey key = Registry.LocalMachine;
Traverse(key, 0);
key.Close();
Console.Read();
}
private static void Traverse(RegistryKey key, int indent)
{
Console.WriteLine(key.Name);
string[] names = key.GetSubKeyNames();
foreach (var subkeyname in names)
{
try
{
string[] valnames = key.GetValueNames();
foreach (string valname in valnames)
{
Console.WriteLine(returnIndentions(indent)+valname + ":" + key.GetValue(valname));
}
Traverse(key.OpenSubKey(subkeyname),indent++);
}
catch {
//do nothing
}
}
}
private static string returnIndentions(int indent)
{
string indentions = "";
for (int i = 0; i < indent; i++) {
indentions += " ";
}
return indentions;
}
}
using System;
using System.Text;
using Microsoft.Win32;
class Program
{
static void Main(string[] args)
{
using RegistryKey key = Registry.LocalMachine;
string keyName = args[0]; // eg #"SOFTWARE\Microsoft\Speech\Voices"
var sb = new StringBuilder();
var subKey = key.OpenSubKey(keyName);
Traverse(subKey);
void Traverse(RegistryKey key, int indent = 0)
{
sb.AppendLine(new string(' ', Math.Max(0, indent - 2)) + key.Name);
indent++;
string[] valnames = key.GetValueNames();
foreach (string valname in valnames)
{
sb.AppendLine(new string(' ', indent) + valname + " : " + key.GetValue(valname));
}
string[] names = key.GetSubKeyNames();
foreach (var subkeyname in names)
{
Traverse(key.OpenSubKey(subkeyname), indent + 2);
}
}
Console.WriteLine(sb.ToString());
}
}