Let's say I have an array of strings:
string[] greeting = new string[] {"hey", "hello", "hi"};
if the user input is any of the following words: "hey" "hello" "hi" then I want the console to print "hey there". This is what I did:
string userInput = Console.ReadLine();
bool result_a = userInput.StartsWith(greeting);
if(result_a) { Console.WriteLine("hey there"); }
but that doesn't seem to be working.
If what you want is, whenever the user starts with any of the 3
using System;
using System.Linq;
...
string[] greeting = new string[] {"hey", "hello", "hi"};
string userInput = Console.ReadLine();
bool result_a = greeting.Any(a => userInput.Trim().StartsWith(a));
if(result_a) { Console.WriteLine("hey there"); }
Example: "hi my name is Ali"
Now if you want capital letters to work as well you need to change the line to:
Example: "Hi my name is Ali"
bool result_a = greeting.Any(a => userInput.Trim().ToLower().StartsWith(a));
If what you want is, whenever the user input contains then:
using System;
using System.Linq;
...
string[] greeting = new string[] {"hey", "hello", "hi"};
string userInput = Console.ReadLine();
bool result_a = greeting.Any(a => userInput.Trim().Contains(a));
if(result_a) { Console.WriteLine("hey there"); }
Example: "Good morning! hello"
Now if you want capital letters to work as well you need to change the line to:
Example: "Good morning! Hello"
bool result_a = greeting.Any(a => userInput.Trim().ToLower().Contains(a));
string[] greeting = new string[] { "hey", "hello", "hi" };
string userInput = Console.ReadLine();
bool result_a = greeting.Any(x=>x.StartsWith(userInput));
if (result_a) { Console.WriteLine("hey there"); }
if (result_a) { Console.WriteLine($"{greeting.FirstOrDefault(x => x.StartsWith(userInput))} there"); }
try this,bro
List<string> greeting = new List<string>();
greeting.Add("hey");
greeting.Add("hello");
greeting.Add("hi");
string userInput = Console.ReadLine();
if (greeting.Contains(userInput.Trim()))
{
Console.WriteLine("hey there");
}
Related
I have to split this:
string text = "John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow";
A logic must be created that will separately extract data from this record:
first name;
last name;
place of birth.
In other words, the displayed String must be edited using the method of the String class and each person's data must be extracted separately. The main method to use is to classify Strings on multiple parts.
string text = " John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow";
string[] textArray = text.Split('"', ' ');
Console.WriteLine("Date: ");
foreach (string str in textArray)
{
for (int i = 0; i < textArray.Length; i++)
{
string[] FirstName = textArray[i].Split(' ');
string[] LastName = textArray[i].Split('.');
string[] BirthPlace = textArray[i].Split('/');
Console.WriteLine($"First name: {FirstName} Last Name: {LastName} BirthPlace: {BirthPlace}");
}
}
For some reason you were iterating your array twice.
string text = " John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow";
string[] textArray = text.Trim().Split(" ");
Console.WriteLine($"Date: {DateTime.Now} ");
String[] delimiters = { ".", "/" };
for (int i = 0; i < textArray.Length; i++)
{
String[] parts = textArray[i].Split(delimiters,StringSplitOptions.None);
Console.WriteLine($"First name: {parts[0]} Last Name: {parts[1]} BirthPlace: {parts[2]}");
}
}
using System.Text.RegularExpressions;
string pattern = #" *(?<FirstName>\w+)\.(?<LastName>\w+)/(?<BirthPlace>\w+)";
string input = " John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow";
MatchCollection m = Regex.Matches(input, pattern, RegexOptions.IgnoreCase);
foreach (Match match in m)
{
Console.WriteLine($"First name: {match.Groups["FirstName"]} Last Name: {match.Groups["LastName"]} BirthPlace: {match.Groups["BirthPlace"]}");
}
You're not using the split method properly. Also would be nice to structure the parsing in a Try method which handles errors also. Here's an example:
static bool TryParseRecord(string record, out string firstName, out string lastName, out string birthPlace)
{
firstName = lastName = birthPlace = "";
record = record.Trim();
if (string.IsNullOrEmpty(record))
{
return false;
}
// parse for birth place
var stringSplit = record.Split('/');
if (stringSplit.Length == 2)
{
record = stringSplit[0];
birthPlace = stringSplit[1];
}
else
{
return false;
}
// parse for names
stringSplit = record.Split('.');
if (stringSplit.Length == 2)
{
firstName = stringSplit[0];
lastName = stringSplit[1];
}
else
{
return false;
}
return !string.IsNullOrEmpty(birthPlace) && !string.IsNullOrEmpty(firstName) && !string.IsNullOrEmpty(lastName);
}
With this, your main would become something like:
static void Main()
{
var text = " John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow";
var textArray = text.Split(' ');
Console.WriteLine("Date: ");
foreach (var entry in textArray)
{
if (TryParseRecord(entry, out var FirstName, out var LastName, out var BirthPlace))
{
Console.WriteLine($"First name: {FirstName}, Last Name: {LastName}, Birth place: {BirthPlace}");
}
}
}
I would start by defining a class to hold the data.
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string PlaceOfBirth { get; set; }
public Person(string firstName, string lastName, string placeOfBirth)
{
FirstName = firstName;
LastName = lastName;
PlaceOfBirth = placeOfBirth;
}
}
I would then define a class to do the extracting.
The original string seperates each Person by a space, so the first thing we need is to split on the space character. This gives an array with three strings.
John.Davidson/Belgrade
Michael.Barton/Krakow
Ivan.Perkinson/Moscow
Again we can use the Split() function to first split the string to get the names and the place of birth, and then to seperate the first name and the last name.
string[] data = personData.Split('/');
string[] names = data[0].Split('.');
Lastly we simple loop the array, and call the constructor for the Person. Combine it all in a class:
public class PersonDataExtractor
{
public static List<Person> ExtractData(string text)
{
string[] peopleData = text.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
var personDataList = new List<Person>();
foreach (string personData in peopleData)
{
string[] data = personData.Split('/');
string[] names = data[0].Split('.');
string firstName = names[0];
string lastName = names[1];
string placeOfBirth = data[1];
personDataList.Add(new Person(firstName, lastName, placeOfBirth));
}
return personDataList;
}
}
This is also easy to unit test. Here with xUnit
public class PersonDataExtractorTests
{
[Fact]
public void ExtractPersonData_ValidInput_ExtractsDataCorrectly()
{
// Arrange
string text = "John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow";
// Act
var personDataList = PersonDataExtractor.ExtractData(text);
// Assert
Assert.Equal(3, personDataList.Count);
Assert.Equal("John", personDataList[0].FirstName);
Assert.Equal("Davidson", personDataList[0].LastName);
Assert.Equal("Belgrade", personDataList[0].PlaceOfBirth);
Assert.Equal("Michael", personDataList[1].FirstName);
Assert.Equal("Barton", personDataList[1].LastName);
Assert.Equal("Krakow", personDataList[1].PlaceOfBirth);
Assert.Equal("Ivan", personDataList[2].FirstName);
Assert.Equal("Perkinson", personDataList[2].LastName);
Assert.Equal("Moscow", personDataList[2].PlaceOfBirth);
}
}
we do it in python like this:
text = " John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow"
for record in text.split(" "):
if record != "":
temp, city = record.split("/")
name, surname = temp.split(".")
print(f"First name: {name} Last Name: {surname} BirthPlace: {city}")
and I converted it to c#:
using System;
public class Program
{
public static void Main()
{
string text = " John.Davidson/Belgrade Michael.Barton/Krakow Ivan.Perkinson/Moscow";
string[] textArray = text.Split('"', ' ');
foreach (string str in textArray)
{
if(str == ""){
continue;
}
string[] temp = str.Split('/');
string city = temp[1];
temp = temp[0].Split('.');
string name = temp[0];
string surname = temp[1];
Console.WriteLine("First name: "+name+" Last Name: "+surname+" BirthPlace: "+city);
}
}
}
I'm working on language wise numbers and I'm doing it via CultureInfo.
CultureInfo class provide Native digit for Arabic and Gujarati language but not for Hindi.
For example:
My number is in English: 123456
Same number in Gujarati language: ૧૨૩૪૫6 (This is working fine)
For English language: १२३४५६ This is not working
What is the alternate option to display Hindi Native digit?
Example :
I want to display numbers in Hindi language: ०,१,२,३,४,५,६,७,८,९.
Here Is my code snippet:
CultureInfo languageculture = new CultureInfo("hi-IN");
NumberFormatInfo languageNumberFormat = languageculture.NumberFormat;
string[] nativeDigits = languageNumberFormat.NativeDigits;
string str5 = ConvertToMyLanguageDigits(i.ToString(), mydiditesgu);
Conversion (replace number) method:
private static string ConvertToMyLanguageDigits(string number, string[] myNative)
{
string myNewMuber = string.Empty;
myNewMuber = number;
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
string number1 = rgx.Replace(number, "");
var aa = number1.ToCharArray().Distinct().ToArray();
foreach (var item in aa)
{
if (!myNative.Any(x => x.Contains(item)))
{
myNewMuber = myNewMuber.Replace(item.ToString(), myNative[int.Parse(item.ToString())].ToString());
}
}
return myNewMuber;
}
Assuming you have the language pack installed on Windows, can't you do.
var hindiCulture = new CultureInfo("hi-IN");
To get the right culture. Then
var hindiDigits = hindiCulture.NumberFormat.NativeDigits;
to get the right digits?
For example, as demonstrated here
using System;
using System.Globalization;
public class Program
{
public static void Main()
{
var hindiCulture = new CultureInfo("hi-IN");
Console.WriteLine(hindiCulture.EnglishName);
Console.WriteLine(hindiCulture.NativeName);
Console.WriteLine(string.Join("", hindiCulture.NumberFormat.NativeDigits));
}
}
outputs
Hindi (India)
हिंदी (भारत)
०१२३४५६७८९
As demonstrated here, If I do
using System;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Linq;
public class Program
{
public static void Main()
{
var hindiCulture = new CultureInfo("hi-IN");
Console.WriteLine(hindiCulture.EnglishName);
Console.WriteLine(hindiCulture.NativeName);
Console.WriteLine(string.Join("", hindiCulture.NumberFormat.NativeDigits));
Console.WriteLine(
ConvertToMyLanguageDigits("0123456789",
hindiCulture.NumberFormat.NativeDigits));
}
private static string ConvertToMyLanguageDigits(string number, string[] myNative)
{
string myNewMuber = string.Empty;
myNewMuber = number;
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
string number1 = rgx.Replace(number, "");
var aa = number1.ToCharArray().Distinct().ToArray();
foreach (var item in aa)
{
if (!myNative.Any(x => x.Contains(item)))
{
myNewMuber = myNewMuber.Replace(
item.ToString(),
myNative[int.Parse(item.ToString())].ToString());
}
}
return myNewMuber;
}
}
The output is
Hindi (India)
हिंदी (भारत)
०१२३४५६७८९
०१२३४५६७८९
There is no problem with your code or with .Net, I suspect you don't have you system set up properly, do you have the language pack installed?
I need to see if string starts with a given string but I am getting ambiguity, here is my code:
string input = "balance1234";
string[] arr = new string[]
{
"bal",
"balance",
};
foreach (string s in arr)
{
if (input.StartsWith(s))
{
var rq= input.Replace(s, "");
}
}
If input is balance1234 , the if condition has to satisfy only with balance, but in my code it is satisfying with bal first.
Here is the solution (using the Hint given by Mr. Skeet):
string input = "balance1234";
string[] arr = new string[]
{
"bal",
"balance",
};
string rq = input;
foreach (string s in arr.OrderByDescending(x => x.Length))
{
if (input.StartsWith(s))
{
rq = input.Replace(s, "");
break;
}
}
Hey, I'm trying to replace some symbols in file. I made dictionary
and I can replace it in my string that I input. How to read my file,
do my replace and save it to another?
class Program
{
static void Main(string[] args)
{
Translit translit = new Translit();
StreamReader sr = new StreamReader("test.txt");
string testIn = "iconb "; //a test input string
string testOut = translit.TranslitFileName(testIn);
Console.WriteLine("Inputed \'{0}\'", testIn);
Console.WriteLine("after \'{0}\'", testOut);
Console.ReadLine();
}
public class Translit
{
Dictionary<string, string> dictionaryChar = new Dictionary<string, string>()
{
{"а","a"},
{"е","e"},
{"о","o"},
{"р","p"},
{"с","c"}
};
public string TranslitFileName(string source)
{
var result = "";
//symbols for replace
foreach (var ch in source)
{
var ss = "";
//compare dictionary keys
if (dictionaryChar.TryGetValue(ch.ToString(), out ss))
{
result += ss;
}
else result += ch;
}
return result;
}
}
}
Try doing it this way:
Func<string, string> map = new []
{
new { input = 'a', output = 'x' },
new { input = 'e', output = 'x' },
new { input = 'o', output = 'x' },
new { input = 'p', output = 'x' },
new { input = 'c', output = 'x' },
}
.Select(x => (Func<string, string>)(s => s.Replace(x.input, x.output)))
.Aggregate((f0, f1) => x => f1(f0(x)));
File.WriteAllText("output.text", map(File.ReadAllText("test.txt")));
Calling map("Hello") produces "Hxllx" given my map code above.
how to create regex to fetch the particular(bug.updateBug) string from the following line available in the log file as follows:
WX Edit Bug: 3550704 Server: servername User:testuser appGUID: appguidvalue Elapsed Time: 624ms method:bug.updateBug Date: Wed May 01 09:38:01 PDT 2013
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApplication59
{
class Program
{
static void Main(string[] args)
{
IEnumerable<string> textLines
= Directory.GetFiles(#"C:\testlocation\", "*.*")
.Select(filePath => File.ReadLines(filePath))
.SelectMany(line => line);
List<string> users = new List<string>();
Regex r = new Regex("^.*WX\\sADVSearch(.*)50\\]$");
foreach (string Line in textLines)
{
if (r.IsMatch(Line))
{
users.Add(Line);
}
}
string[] textLines1 = new List<string>(users).ToArray();
int countlines = textLines1.Count();
Console.WriteLine("WX_ADVSearch=" + countlines);
// keep screen from going away
// when run from VS.NET
Console.ReadLine();
}
}
}
It seems that you have data in the form of something like key/value pair. Try using this regex:
(?<=method\:)([^ ]+)
Here:
method is the key whose value is to be find.
and any thing except the next key is supposed to be its value.
Hope it helps!
EDIT
static void Main(string[] args)
{
IEnumerable<string> textLines = Directory.GetFiles(#"C:\testlocation\", "*.*")
.Select(filePath => File.ReadLines(filePath))
.SelectMany(line => line);
//List<string> users = new List<string>();
//Regex r = new Regex("^.*WX\\sADVSearch(.*)50\\]$");
string text = String.Join("",textLines.ToArray());
MatchCollection mcol = Regex.Matches(text,"(?<=method\:)([^ ]+)");
//foreach (string Line in textLines)
//{
// if (r.IsMatch(Line))
// {
// users.Add(Line);
// }
//}
//string[] textLines1 = new List<string>(users).ToArray();
int countlines = mcol.Count; //textLines1.Count();
Console.WriteLine("WX_ADVSearch=" + countlines);
// keep screen from going away
// when run from VS.NET
Console.ReadLine();
}