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
Related
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 want to extract all decimal/ integer value before a character sequence(am/AM) until an alphabet or a special charecter comes up value
Input Output
PEK\n2545 AMAzerbhaijan 2545
PEK\n2545 AMamorphous 2545
ANGwwquui\3.0 amAm 3.0
Awyu&&#^/Non-Prog//#*(*889/328.19 am -> 328.19
qii2781a/k28U28am 28
PEK\nam2545 AM 2545
Can I know what is the best possible way to do this? Thanks in advance.
Given the examples you showed, I believe this would do the trick:
public string ParseData(string input)
{
StringBuilder numberBuilder = new StringBuilder();
string terminatorChars = "am";
bool isCaseSensitive = false;
int terminatorCharLength = terminatorChars.Length;
for (int i = 0; i < input.Length; i++)
{
if (input.Length - i >= terminatorCharLength)
{
var currentSubstr = input.Substring(i, terminatorCharLength);
if ((currentSubstr == terminatorChars) || (!isCaseSensitive && currentSubstr.ToLowerInvariant() == terminatorChars.ToLowerInvariant()))
if(numberBuilder.Length>0)
return numberBuilder.ToString();
}
if (Char.IsDigit(input[i]) || input[i] == '.')
numberBuilder.Append(input[i]);
else if (Char.IsWhiteSpace(input[i]))
continue;
else
numberBuilder.Clear();
}
return null;
}
The data is fixed width data with name the first 50 character and value the data after column 50. See code below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.txt";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(FILENAME);
string line = "";
List<KeyValuePair<string, decimal>> data = new List<KeyValuePair<string,decimal>>();
int lineNumber = 0;
while((line = reader.ReadLine()) != null)
{
if(++lineNumber > 1)
{
string key = line.Substring(0, 50).Trim();
decimal value = decimal.Parse(line.Substring(50));
data.Add(new KeyValuePair<string,decimal>(key,value));
}
}
}
}
}
I need to design a program that reads in an ASCII text file and creates an output file that contains each unique ASCII character and the number of times it appears in the file. Each unique character in the file must be represented by a character frequency class instance. The character frequency objects must be stored in an array list. My code is below:
using System.IO;
using System;
using System.Collections;
namespace ASCII
{
class CharacterFrequency
{
char ch;
int frequency;
public char getCharacter()
{
return ch;
}
public void setCharacter(char ch)
{
this.ch = ch;
}
public int getfrequency()
{
return frequency;
}
public void setfrequency(int frequency)
{
this.frequency = frequency;
}
static void Main()
{
string OutputFileName;
string InputFileName;
Console.WriteLine("Enter the file path");
InputFileName = Console.ReadLine();
Console.WriteLine("Enter the outputfile name");
OutputFileName = Console.ReadLine();
StreamWriter streamWriter = new StreamWriter(OutputFileName);
string data = File.ReadAllText(InputFileName);
ArrayList al = new ArrayList();
//create two for loops to traverse through the arraylist and compare
for (int i = 0; i < data.Length; i++)
{
int k = 0;
int f = 0;
for (int j = 0; j < data.Length; j++)
{
if (data[i].Equals(data[j]))
{
f++;
if (i > j) { k++; }
}
}
al.Add(data[i] + "(" + (int)data[i] + ")" + f + " ");
foreach (var item in al)
{
streamWriter.WriteLine(item);
}
}
streamWriter.Close();
}
}
}
When I run the program, the program does not stop running and the output file keeps getting larger until it eventually runs out memory and I get an error stating that. I am not seeing where the error is or why the loop won't terminate. It should just count the characters but it seems to keep looping and repeating counting the characters. Any help?
Try this approach :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace yourNamespace
{
class Char_frrequency
{
Dictionary<Char, int> countMap = new Dictionary<char, int>();
public String getStringWithUniqueCharacters(String input)
{
List<Char> uniqueList = new List<Char>();
foreach (Char x in input)
{
if (countMap.ContainsKey(x))
{
countMap[x]++;
}
else
{
countMap.Add(x, 1);
}
if (!uniqueList.Contains(x))
{
uniqueList.Add(x);
}
}
Char[] uniqueArray = uniqueList.ToArray();
return new String(uniqueArray);
}
public int getFrequency(Char x)
{
return countMap[x];
}
}
}
This might not be the ideal solution. But you can use these methods
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.
Given a string of n lines like:
start-student--subject--end-student--start-student-marks-end-student-
-start-student-total-end-student-names of students-student-details-percentage-end-student-details--start-student-subject-end-student--start-student-marks-end-student-
-start-student-total-end-student-class-start-student-percentage-end-student-
My approach:
string s = File.ReadAllText(#"D:\Data.txt");
int start = s.IndexOf("start-student") + 1;
int end = s.IndexOf("end-student", start);
string result = s.Substring(start, end - start);
Console.WriteLine(result);
i'm getting only one string:
"subject"
Thanks in Advance
You can solve this using regular expressions:
using System;
using System.IO;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string s = File.ReadAllText(#"D:\Data.txt");
var matches = Regex.Matches(s, "(?<=start-student)((?!end-student).)*");
foreach(var m in matches)
{
Console.Out.WriteLine(m);
}
}
}
Produces
--subject--
-marks-
-total-
-subject-
-marks-
-total-
-percentage-
string s = File.ReadAllText(#"D:\SampleXML.txt");
Regex r = new Regex(#"start-student-(.+?)-end-student");
MatchCollection mc = r.Matches(s);
string[] c = new string[mc.Count];
for (int i = 0; i < mc.Count; i++)
{
c[i] = mc[i].Groups[0].Value;
}
string result = string.Join("\n", c);
Console.WriteLine(result);