I am new to C#.
How do I take user input and save each letter I type as a separate entity in an array.
I want to scan through the array and find a particular sequence of characters to act as a starting point.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter Nitrogenous base sequence");
string[] sequence = new string[]{Console.ReadLine()};
foreach(string a in sequence)
{
if(a=="TATAAT")
{
Console.WriteLine("YAAY");
}
else
{
Console.WriteLine("NO");
You can think of a string as a glorified character array.
var pattern = "TATAAT";
var input = Console.ReadLine();
var patternIndex = input.IndexOf(pattern);
if(patternIndex >= 0) {
var answer = input.Substring(patternIndex + pattern.Length, 4);
Console.WriteLine("YAAY: " + answer);
} else {
Console.WriteLine("NO");
}
You can do this using LINQ, this will get the input from user then save each character as string into an array:
string[] sequence = Console.ReadLine().Select(x => x.ToString()).ToArray();
If you don't want to include spaces:
string[] sequence = Console.ReadLine().Where(x => !char.IsWhiteSpace(x))
.Select(x => x.ToString())
.ToArray();
Related
Below code if for reverse word in a sentence, the word sequence in the sentence will be same but the word will be reversed
using System;
using System.Text;
namespace reverse_a_string
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a string: ");
string S = Console.ReadLine();
string[] sep = S.Split(" ");
StringBuilder Wrev = new StringBuilder(); //Word reverse
StringBuilder Srev = new StringBuilder(); //Sentence reverse
for (int j=0;j<sep.Length;j++)
{
for (int i = sep[j].Length - 1; i >= 0; i--)
{
Wrev.Append(sep[j][i]);
}
Srev.Append(Wrev);
Wrev.Clear();
Wrev.Append(" ");
}
Console.WriteLine(Srev);
}
}
}
For simple text, you can just use Split, Reverse, Concat and Join
var words = Console.ReadLine()
.Split()
.Select(x => string.Concat(x.Reverse()));
Console.WriteLine(string.Join(" ", words));
Output
Enter a string: asd sdf dfg fgh
dsa fds gfd hgf
For complicated Unicode, you will need to be more precise in the grouping of characters. However, you can take advantage of GetTextElementEnumerator
Returns an enumerator that iterates through the text elements of a
string.
Given
public static IEnumerable<string> ToElements(this string source)
{
var enumerator = StringInfo.GetTextElementEnumerator(source);
while (enumerator.MoveNext())
yield return enumerator.GetTextElement();
}
Usage
var words = Console.ReadLine()
.Split()
.Select(x => string.Concat(x.ToElements().Reverse()));
static void Main(string[] args)
{
//method 1
Console.Write("Enter a string: ");
string sentence = Console.ReadLine();
string[] words = sentence.Split(" ");
StringBuilder destination = new StringBuilder(); //Sentence reverse
foreach (string word in words)
{
destination.Append(string.Concat(new string(word.Reverse().ToArray()), " "));
}
Console.WriteLine(destination);
//method 2 but need import System.Linq namespace.
var reversedWords = string.Join(" ", sentence.Split(' ').Select(x => new String(x.Reverse().ToArray())));
Console.WriteLine(reversedWords);
}
Let's start from definition; assuming that
Word is a non-empty sequence of letters and apostrophes
we can implement a simple solution with a help of regular expressions (and a pinch of Linq - Reverse()): all we have to do is to Replace each word with its Reversed representation.
Code:
using System.Linq;
using System.Text.RegularExpressions;
...
private static string WordReverse(string value) =>
Regex.Replace(value ?? "", #"[\p{L}_]+", m => string.Concat(m.Value.Reverse()));
Demo:
string[] tests = new string[] {
"Text (на русском)",
"Simple test.",
"Another \"text\": punctuation!"
};
Console.Write(string.Join(Environment.NewLine, tests
.Select(test => $"{test,-30} => {WordReverse(test)}")));
Outcome:
Text (на русском) => txeT (ан мокссур)
Simple test. => elpmiS tset.
Another "text": punctuation! => rehtonA "txet": noitautcnup!
This question already has answers here:
How do I create a terminable while loop in console application?
(7 answers)
Closed 3 years ago.
I started a C# course now and there is an assignment where I have to create a "palindrome detector" program. Point is that user inputs some word or sentence, then I have to remove chars like ,.;:!? and space from it. I have done that with two different methods, because char method can not remove space so I wrote another method for it.
After "cleaning" operation program reversing input what user gave, and comparing original user input and reversed user input to each other. It they are same it prints "It is palindrome", if they are different it prints "It is not palindrome". That is working fine, BUT THE PROBLEM IS I have to put them in for loop. It have to ask input again and again, until user give empty.
This would be very easy, but somehow I can not do it.
Here is my code:
using System;
namespace Palindromi
{
class Program
{
static void Main()
{
Console.WriteLine("Hei! Tervetuloa palindromin tunnistusohjelmaan. Tämä tunnistaa, onko syöttämäsi sana sama toisinpäin!");
Console.Write("Anna teksti (tyhjä lopettaa): ");
string userinput = Console.ReadLine(); //userinput is user's input, this is what you have to modify. remove some chars and reverse it.
if (userinput == "")
{
Console.ReadLine();//when i have loop this have to be "break". This meant to break for loop when i have it.
}
char[] removechars = { '.', ':', ';', ',', '!', '?' };//this is the list of "have to be removed" chars
string userinput_without_chars = userinput.Trim(removechars); //this method remove chars which are listed
string userinput_without_chars_space = userinput_without_chars.Replace( " ", ""); //replace space with empty
string reverse_string, reversed;
reverse_string = userinput_without_chars_space;
reversed = "";
int len;
len = userinput_without_chars_space.Length - 1;
while (len >= 0)
{
reversed = reversed + reverse_string[len];
len--;
}
Console.WriteLine("Sana käännettynä on {0}", reversed); //tells user input reversed
if (userinput_without_chars_space == reversed)//check is the userinput same than reversed user input
{
Console.Write("On palindromi.");//it is palindrome
}
else
{
Console.Write("Ei ole palindromi.");//it is not palindrome
}
}
}
}
You could potentially do something along these lines:
var running = true;
while(running)
{
var input = Console.ReadLine().ToLower();
var phrase = input.Sanitize(new List<string>() {".", ",", "?", "!", "'", "&", "%", "$", " "});
if(phrase.IsPalindrome())
Console.Writeline("Input was palindrome.");
}
public static string Sanitize(this string input, IList<string> punctuation) =>
String.Join(String.Empty, input.Where(character => punctuation.Contains(character) == false));
public static bool IsPalindrome(this string sentence)
{
for (int l = 0, r = sentence.Length - 1; l < r; l++, r--)
if (sentence[l] != sentence[r])
return false;
return true;
}
public static void Close(string input)
{
// Some logic to see if the application should stop.
}
You could create another method that looks for commands, or keystrokes, then sets the boolean to run as false. Which would break the infinite loop. You could also do an abrupt close with Environment.Exit.
The very simplest approach is replace your Console.ReadLine() where you want to break to return.
Alternatively, you could wrap the logic in another while loop.
while (userinput != "")
{
// Remove chars
// rest of your logic
/* IMPORTANT */
userinput = Console.Readline();
}
To remove the symbols from the input, you can use the Regex.Replace method. In this case, you can be sure, that the specified symbols will be correctly removed from the input string. Note, that you can handle the whitespaces along with other characters you mentioned, like in the code snippet below:
var CharactersToRemove { get; set; } = " ,.;:!?";
var processedInput = Regex.Replace(input.ToLower(), $"[{CharactersToRemove}]", string.Empty);
Note, that here I used input.ToLower() to convert the input to a lowercase string. This will make the palindrome tests case-insensitive. Should you need case-sensitive palindrome tests, just remove the .ToLower() part.
There is no need to reverse the input string to check if it is a palindrome. You can check this within one for loop as follows:
bool CheckForBeingaAPalindrome(string input)
{
var frontIndex = 0;
var tailIndex = input.Length - 1;
for (; frontIndex < tailIndex;)
{
if (input[frontIndex] != input[tailIndex])
return false;
++frontIndex;
--tailIndex;
}
return true;
}
Note, that in this case you only iterate over the elements of the input string once. This approach will give you al least 4 times better performance than the one you used.
Below, you can find a complete minimal working solution to your problem.
using System.Text.RegularExpressions;
using static System.Console;
namespace Assignment
{
public static class PalindromeFinder
{
public static string CharactersToRemove { get; set; } = " ,.;:!?";
public static bool IsPalindrome(string input)
{
var processedInput = RemoveUnnecessaryCharacters(input);
return CheckForBeingAPalindrome(processedInput);
}
private static string RemoveUnnecessaryCharacters(string input)
{
return Regex.Replace(input.ToLower(), $"[{CharactersToRemove}]", string.Empty);
}
private static bool CheckForBeingAPalindrome(string input)
{
var frontIndex = 0;
var tailIndex = input.Length - 1;
for (; frontIndex < tailIndex;)
{
if (input[frontIndex] != input[tailIndex])
return false;
++frontIndex;
--tailIndex;
}
return true;
}
}
public class Program
{
private static void Main(string[] args)
{
ContinuouslyCheckUserInputForBeingAPalindrome();
}
private static void ContinuouslyCheckUserInputForBeingAPalindrome()
{
while (FetchUserInputFromConsole() is string input
&& !string.IsNullOrWhiteSpace(input))
{
var isPalindrome = PalindromeFinder.IsPalindrome(input);
var modifier = isPalindrome ? "a" : "not a";
WriteLine($"It is {modifier} palindrome");
}
}
private static string FetchUserInputFromConsole()
{
Write("Enter a string: ");
return ReadLine();
}
}
}
I have a text file that a list of these words on it
Laptop
Laser
Macho
Sam
Samantha
Mulder
Microphone
Aardvark
And what I want to do is have user input type in a word and the console will basically respond with we have your word or we do not have your word. This is my code so far:
TextReader file = new StreamReader("Files/Exercise_Files/Words.txt");
Console.WriteLine("Welcome to FindWord");
string wordInput;
Console.WriteLine("Type in a word so we can try and find it: ");
wordInput = Console.ReadLine();
string sLine = file.ReadToEnd();
if (String.Compare(wordInput, sLine, true) == 0)
{
Console.WriteLine("We have found your word!");
}
else
{
Console.WriteLine("We have not found your word");
}
file.Dispose();
I have tried doing a couple of versions trying to solve this and one included adding a for-each loop but that confused me quite a bit. I'm not 100% sure when to use a for-each loop. I also want to have string comparison be case insensitive but the code I have now will always say word not found no matter what I input.
You can use the File.ReadAllLines() method to read the file lines into an array, and then the Linq extension method Contains to determine if a word exists in that list (and you can do a case-insensitive search):
static void Main(string[] args)
{
var filePath = #"c:\temp\temp.txt";
var words = File.ReadAllLines(filePath);
Console.Write("Enter a search term: ");
var searchTerm = Console.ReadLine();
if (words.Contains(searchTerm, StringComparer.OrdinalIgnoreCase))
{
Console.WriteLine("We have your word!");
}
else
{
Console.WriteLine("We do not have your word");
}
Console.ReadKey();
}
Load file into array
string[] words = File.ReadAllLines(path);
Then use LINQ to find
if (words.Any(w => string.Equals(w, input, StringComparison.InvariantCultureIgnoreCase)))
// do your thing here
Performance Contains vs Any
Contains is quicker but in this case difference will not be visible since searched collection is small.
public class Program
{
public static HashSet<string> _hs = new HashSet<String>(Enumerable.Range(1,1000).Select(x=> "Item " + x));
public static string[] _arr = Enumerable.Range(1,1000).Select(x=> "Item " + x).ToArray();
public static void Main()
{
var sw = new Stopwatch();
sw.Start();
bool f;
for (int i = 1; i < 1001; i++)
{
//f = _hs.Contains("Item " + i, StringComparer.OrdinalIgnoreCase);
f = _arr.Contains("Item " + i, StringComparer.OrdinalIgnoreCase);
}
Console.WriteLine(sw.Elapsed);
sw.Restart();
for (int i = 1; i < 1001; i++)
{
f = _hs.Any(w => string.Equals(w, "Item " + i, StringComparison.InvariantCultureIgnoreCase));
}
Console.WriteLine(sw.Elapsed);
}
}
String.Compare , compares two strings. I think, you may want to use Contains method. Please see below-
if (sLine.Contains(wordInput))
{
Console.WriteLine("We have found your word!");
}
else
{
Console.WriteLine("We have not found your word");
}
I am writing a simple console application to would allow me to count the occurrence of each unique word.
for example the console will allow the user to type a sentence, once press enter the system should count the number of time each words occurs. so far I can only count characters. any help would be appreciated.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter string");
string input = Convert.ToString(Console.ReadLine());
Dictionary<string, int> objdict = new Dictionary<string, int>();
foreach (var j in input)
{
if (objdict.ContainsKey(j.ToString()))
{
objdict[j.ToString()] = objdict[j.ToString()] + 1;
}
else
{
objdict.Add(j.ToString(), 1);
}
}
foreach (var temp in objdict)
{
Console.WriteLine("{0}:{1}", temp.Key, temp.Value);
}
Console.ReadLine();
}
}
Try this method:
private void countWordsInALIne(string line, Dictionary<string, int> words)
{
var wordPattern = new Regex(#"\w+");
foreach (Match match in wordPattern.Matches(line))
{
int currentCount=0;
words.TryGetValue(match.Value, out currentCount);
currentCount++;
words[match.Value] = currentCount;
}
}
Call the above method like this:
var words = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase);
countWordsInALine(line, words);
In the words dictionary you will find the words (key) along with its occurance frequency (value).
Just call Split method passing single space (assuming word is seperated by single space) and it would give collection of each word then iterate over each element of collection with the same logic you were having.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please enter string");
string input = Convert.ToString(Console.ReadLine());
Dictionary<string, int> objdict = new Dictionary<string, int>();
foreach (var j in input.Split(" "))
{
if (objdict.ContainsKey(j))
{
objdict[j] = objdict[j] + 1;
}
else
{
objdict.Add(j, 1);
}
}
foreach (var temp in objdict)
{
Console.WriteLine("{0}:{1}", temp.Key, temp.Value);
}
Console.ReadLine();
}
}
You need to split the string on spaces (or any other characters which you consider to delimit words). Try changing the loop to this:
foreach (string Word in input.Split(' ')) {
}
Might I suggest a ternary-tree to make things efficient?
Here's a link to a C# implementation: http://igoro.com/archive/efficient-auto-complete-with-a-ternary-search-tree/
After first inserting into the tree, you could simply call "Contains" with one of the implementations above to make things quick
Try this...
var theList = new List<string>() { "Alpha", "Alpha", "Beta", "Gamma", "Delta" };
theList.GroupBy(txt => txt)
.Where(grouping => grouping.Count() > 1)
.ToList()
.ForEach(groupItem => Console.WriteLine("{0} duplicated {1} times with these values {2}",
groupItem.Key,
groupItem.Count(),
string.Join(" ", groupItem.ToArray())));
Console.ReadKey();
http://omegacoder.com/?p=792
here is my code:
class Program
{
static void Main(string[] args)
{
string sentence = string.Empty;
sentence = Console.ReadLine();
string[] sent = sentence.Split(' ');
//to be sorted alphabetically
var x =
from k in sent
orderby k
select k;
foreach (string s in x)
{
Console.WriteLine(s.ToLower());
}
Console.ReadLine();
}
}
is there any method to find and remove duplicate words or I should make my own method?
You could use Linq's Distinct extension method:
var sent = sentence.Split(' ').Distinct();
You can also use this to ignore the case of strings when comparing them—e.g. "WORD" and "word" would be considered duplicates:
var sent = sentence.Split(' ').Distinct(StringComparer.CurrentCultureIgnoreCase);
Use System.Linq Distinct:
foreach (string s in x.Distinct())
Use Distinct:
foreach (string s in x.Distinct())
{
Console.WriteLine(s.ToLower());
}
This should do everything you're asking:
class Program
{
static void Main(string[] args)
{
string sentence = string.Empty;
sentence = Console.ReadLine();
var sent = sentence
.Split(' ')
.Distinct()
.OrderBy(x => x);
foreach (string s in sent)
{
Console.WriteLine(s.ToLower());
}
Console.ReadLine();
}
}
Hope it helps!