User input in console: jack look
What I want to do is to create two arraylists with jack and look. To achieve this I first analyzed jack and look separately and send them to arraylist name words(); The hard part of this is input can contain 3 or 100 words.
I need to define arraylist size of words.count. It is like arraylist in arraylist...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Text.RegularExpressions;
namespace ConsoleApplication33
{
class Program
{
static void Main(string[] args)
{
int ü = 0;
while (ü == 0)
{
ArrayList words = new ArrayList();
ArrayList merdum = new ArrayList();
string s = Console.ReadLine();
string[] kelimeler = s.Split(' ');
for (int i = 0; i < kelimeler.Length; i++)
{
string a = kelimeler[i];
string[] kökler = Regex.Split(a, #"\W+");
words.Add(kökler);
foreach (string kelime in kökler)
{
Console.WriteLine(kelime);
}
}
words.Sort();
int count = words.Count;
for (int i = 0; i < count; i++)
{
ArrayList words(i) =new ArrayList();
// this is where i need help
}
words.Add(kelimeler);
Console.ReadKey();
}
}
// # special verbatim string synta
// \W+ one or more non-word characters together
}
}
I would recommend using multi-dimensional arrays instead if you are using a for loop inside a foor loop. If that´s something you didn´t already think about of course.
Related
I need to import a number of characters in a string format with a comma and check if a string is valid by containing all of them. The string must be in a format like that "AB2345CD" . This is the code I have for now but i dont know how to check if it is valid by containing all of the input characters and every digit between 0 and 9.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace License_Plates
{
class Program
{
static void Main(string[] args)
{
string input = Console.ReadLine();
var allowedCharacters = input.ToList();
int platesToValidate = int.Parse(Console.ReadLine());
List<string> plateNumbers = new List<string>();
for (int i = 0; i < platesToValidate; i++)
{
string plate = Console.ReadLine();
plateNumbers.Add(plate);
}
List<string> validNumbers = new List<string>();
foreach (var number in plateNumbers)
{
if (number.Contains(allowedCharacters.ToString()))
{
validNumbers.Add(number);
}
}
for (int i = 0; i < validNumbers.Count; i++)
{
Console.WriteLine(i);
}
}
}
}
Check if string contains all required characters
you could use the linq extension All:
var allowedstring = "A,B,C,D";
var allowednumber = "0,1,2,3,4,5,6,7,8,9";
var test1 = "ABC0";
var test2 = "AZ9";
var allowed = $"{allowedstring}{allowednumber}".Replace(",", "");
Console.WriteLine(test1.All(c => allowed.Contains(c))); //True
Console.WriteLine(test2.All(c => allowed.Contains(c))); //False
The task is to read from a file, retrieve words (no numbers or special characters) and adding it to a hash table. If the same word (key) already exist in the hash table, update the frequency of the word(value) +1.
So far in the code blow, all text is retrieved from the file including words with numbers and special characters into a string array "words".
I would like to update the values based on a regex to only keep words with letters, in lowercase.
I have tried the regex in all different ways but it does not work. The Split() method only allows individual characters to be removed. (eventually, this code will need to be applied to 200 files with unknown amount of special characters and numbers).
Is there a clean way to read the file, save only words and omit special characters and numbers?
this is what i have so far:
using System;
using System.Collections.Generic;
using System.Collections;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
String myLine;
String[] words;
Hashtable hashT = new Hashtable();
TextReader tr = new StreamReader("C:\\file including numbers and spacial charecters.txt");
while ((myLine = tr.ReadLine()) != null)
{
words = myLine.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
string pattern = #"^[a - z] +$";
Regex term = new Regex(pattern);
for (int i = 0; i < words.Length; i++)
{
Console.WriteLine(words[i]);
words[i] = Regex.Replace(words[i], term, "");
if (hashT.ContainsKey(words[0]))
{
hashT[words[i]] = double.Parse(hashT[words[i]].ToString()) + 1;
}
else
{
hashT.Add(words[i], 1.00);
}
}
foreach (String word in hashT.Keys)
{
Console.WriteLine(word + " " + hashT[words]);
}
Console.ReadKey();
}
}
}
}
try this
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
//file content read form your file
string fileContent = #"Hello Wor1d
fun f1nd found
";
//split file content to lines
string[] line = fileContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
Regex r = new Regex("[a-zA-Z]+");
List<string> matchesList = new List<string>();
for (int i = 0; i < line.Length; i++)
{
//split line to string, like Hello Wor1d => string[]{ Hello, Wor1d }
string[] lineData = line[i].Split(' ');
for (int j = 0; j < lineData.Length; j++)
{
string str = lineData[j];
//get matches form string
//if count == 0, string is not include words
//if count > 1 string is have some not words, because Wor1d have 2 matches => Wor and d
if (r.Matches(str).Count == 1)
{
matchesList.Add(str);
}
}
}
for (int i = 0; i < matchesList.Count; i++)
{
Console.WriteLine($"{matchesList[i]} is ok");
}
Console.ReadLine();
}
}
}
I did this code, but it doesnt give summary. Still I can get numbers of each row, but not summary...
using System;
using System.IO;
namespace Progaram
{
class Count
{
static void Main()
{
using (StreamReader sr = new StreamReader("file.txt"))
{
string[] numbers = File.ReadAllLines("file.txt");
int summary = 0;
for (int i = 0; i < numbers.Length; i++)
{
summary += numbers[i];
//Console.WriteLine(numbers[i]);
}
Console.WriteLine(summary);
sr.ReadLine();
}
}
}
}
Your current solution will not compile.
You'll receive the following compilation error:
Cannot convert type 'string' to 'int'.
You'll want to convert the parsed string into an int.
Also, you're using a StreamReader, and reading a single line after reading in all lines. You don't need the StreamReader in this case.
using System;
using System.IO;
namespace Progaram
{
class Count
{
static void Main()
{
string[] numbers = File.ReadAllLines("file.txt");
int summary = 0;
for (int i = 0; i < numbers.Length; i++)
{
summary += Convert.ToInt32(numbers[i]);
}
Console.WriteLine(summary);
}
}
}
You can't add a string to an int.
You need to either convert the entire string array to an int array with
int[] intNumbers = Array.ConvertAll(numbers, int.Parse);
Then index this array instead
summary += intNumbers[i];
Or as Michael suggests, convert numbers[i] before adding
summary += int.Parse(numbers[i]);
The code is to generate random numbers in 100 files numbered from 0..99.
What I couldn't get was why this code ended up creating a file called 100.txt and I even got an exception saying that 100.txt was being written by another process.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RandomNumbersFileGenerator
{
class Program
{
static Random Random = new Random();
static void Main(string[] args)
{
List<Task> tasks = new List<Task>();
for(int fileNumber = 0; fileNumber < 100; ++fileNumber)
{
tasks.Add(Task.Run(()=>GenerateFileWithRandomNumbers(Path.Combine($"c:\\FilesWithRandomNumbers\\{fileNumber}.txt"), 10000000)));
}
Task.WaitAll(tasks.ToArray());
}
static void GenerateFileWithRandomNumbers(string path, int numberOfNumbers)
{
List<string> listOfNumbers = new List<string>();
for(;numberOfNumbers > 0; --numberOfNumbers)
{
listOfNumbers.Add(Random.Next().ToString());
}
File.WriteAllLines(path, listOfNumbers);
}
}
}
It is related to closures and captured variables. Change
for(int fileNumber = 0; fileNumber < 100; ++fileNumber)
{
tasks.Add(Task.Run(()=>GenerateFileWithRandomNumbers(Path.Combine($"c:\\FilesWithRandomNumbers\\{fileNumber}.txt"), 10000000)));
}
To
for(int fileNumber = 0; fileNumber < 100; ++fileNumber)
{
int tmp = fileNumber;
tasks.Add(Task.Run(()=>GenerateFileWithRandomNumbers(Path.Combine($"c:\\FilesWithRandomNumbers\\{tmp}.txt"), 10000000)));
}
See also http://csharpindepth.com/articles/chapter5/closures.aspx
I have strings that look like the following:
"1y 250 2y 32% 3y otherjibberish".
My ultimate goal is to split it into the following:
"1y 250"
"2y 32%"
"3y otherjibberish"
The main 'separator' between these splits are the "\d+y" patterns. Using Regex (C# 4.0), I can use the Matches function to match a number followed by a 'y', but I don't know how to get everything that follows that match but precedes the next match.
Is there a way to do that?
Hopefully that makes sense.... Much appreciated
- kcross
You can use a "MatchCollection" to split the string according to the occurrences.
The example below does almost what you want. The blank character at right of each string is not removed.
Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace Q11438740ConApp
{
class Program
{
static void Main(string[] args)
{
string sourceStr = "1y 250 2y 32% 3y otherjibberish";
Regex rx = new Regex(#"\d+y");
string[] splitedArray = SplitByRegex(sourceStr, rx);
for (int i = 0; i < splitedArray.Length; i++)
{
Console.WriteLine(String.Format("'{0}'", splitedArray[i]));
}
Console.ReadLine();
}
public static string[] SplitByRegex(string input, Regex rx)
{
MatchCollection matches = rx.Matches(input);
String[] outArray = new string[matches.Count];
for (int i = 0; i < matches.Count; i++)
{
int length = 0;
if (i == matches.Count - 1)
{
length = input.Length - (matches[i].Index + matches[i].Length);
}
else
{
length = matches[i + 1].Index - (matches[i].Index + matches[i].Length);
}
outArray[i] = matches[i].Value + input.Substring(matches[i].Index + matches[i].Length, length);
}
return outArray;
}
}
}
Output:
'1y 250 '
'2y 32% '
'3y otherjibberish'
"Solution" 7z file: Q11438740ConApp.7z
This was actually quite easy... Just used the Regex.Split() method.