How to check single array contains same value - c#

string currentUrl = "destination/India/India/mumbai";
string[] array = currentUrl.Split('/');
string countryName = "india";
In the above example,In C# how can i check that Country name is repeating in url?

By Count()ing the appearence of countryName
string currentUrl = "destination/India/India/mumbai";
string[] array = currentUrl.Split('/');
string countryName = "india";
bool isRepeating = array.Count(x => countryName.Equals(x, StringComparison.OrdinalIgnoreCase)) > 1;

you can use the Distinct method. Something like
string currentUrl = "destination/India/mumbai";
string[] array = currentUrl.Split('/');
string countryName = "india";
if (array.Distinct().Count() != array.Count())
{
Console.WriteLine("Duplicate");
}
Or you can try blow code
string currentUrl = "destination/india/india/mumbai";
string[] array = currentUrl.Split('/');
string countryName = "india";
bool r = array.Where(x => x.Equals(countryName)).Count()>1;
if(r)
{
Console.WriteLine("Duplicate");
}

Related

String text split

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);
}
}
}

separate first middle last name C#

Goal: parse name when user enters name, and have a message box display with first middle and last name. Right now it only works when you type in three names, if you try two it crashes, and I'm sure it's cause of my array but Im not sure where I'm wrong. Super novice, learning on my own so any help would be greatly appreciated!!
P.S. GUI the user sees is just an entry block for them to enter their name into one line, spacing between each word.
private void btnParseName_Click(object sender, System.EventArgs e)
{
string fullName = txtFullName.Text;
fullName = fullName.Trim();
string[] names = fullName.Split(' ');
string firstName = "";
string firstLetter = "";
string otherFirstLetters = "";
if (names[0].Length > 0)
{
firstName = names[0];
firstLetter = firstName.Substring(0, 1).ToUpper();
otherFirstLetters = firstName.Substring(1).ToLower();
}
string secondName = "";
string secondFirstLetter = "";
string secondOtherLetters = "";
if (names[1].Length > 0)
{
secondName = names[1];
secondFirstLetter = secondName.Substring(0, 1).ToUpper();
secondOtherLetters = secondName.Substring(0).ToLower();
}
string thirdName = "";
string thirdFirstLetter = "";
string thirdOtherLetters = "";
if (names[2].Length > 0)
{
thirdName = names[2];
thirdFirstLetter = thirdName.Substring(0, 1).ToUpper();
thirdOtherLetters = thirdName.Substring(0).ToLower();
}
MessageBox.Show(
"First Name: " + firstLetter + otherFirstLetters + "\n\n" +
"Middle Name: " + secondFirstLetter + secondOtherLetters + "\n\n" +
"Last Name: " + thirdFirstLetter + thirdOtherLetters);
Here is the working example how you can do it:
public class FullName
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public FullName()
{
}
public FullName(string fullName)
{
var nameParts = fullName.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
if (nameParts == null)
{
return;
}
if (nameParts.Length > 0)
{
FirstName = nameParts[0];
}
if (nameParts.Length > 1)
{
MiddleName = nameParts[1];
}
if (nameParts.Length > 2)
{
LastName = nameParts[2];
}
}
public override string ToString()
{
return $"{FirstName} {MiddleName} {LastName}".TrimEnd();
}
}
Usage example:
class Program
{
static void Main(string[] args)
{
var fullName = new FullName("first middle last");
Console.WriteLine(fullName);
Console.ReadLine();
}
}
You need to check for and handle the second name being empty. Initialising the string will prevent the crash, then checking for input.
string secondName = "";
string secondFirstLetter = "";
string secondOtherLetters = "";
if(names.Length > 2)
{
secondName = names[1];
secondFirstLetter = secondName.Substring(0, 1).ToUpper();
secondOtherLetters = secondName.Substring(0).ToLower();
}
In fact it would be worth intialising all your variables or managing user input validation.
As mentioned in another answer you need assign middle name only when third name exists.
Below approach which uses Dictionary.TryGetValue method and C#7 feature for out parameters.
var textInfo = System.Globalization.CultureInfo.CurrentCulture.TextInfo;
var names = fullName.Split(' ')
.Where(name => string.IsNullOrWhiteSpace(name) == false)
.Select(textInfo.ToTitleCase)
.Select((Name, Index) => new { Name, Index })
.ToDictionary(item => item.Index, item => item.Name);
names.TryGetValue(0, out string firstName);
names.TryGetValue(1, out string middleName);
if (names.TryGetValue(2, out string lastName) == false)
{
lastName = middleName;
middleName = null;
}
// Display result
var result = new StringBuilder();
result.AppendLine("First name: ${firstName}");
result.AppendLine("Middle name: ${middleName}");
result.AppendLine("Last name: ${lastName}");
MessageBox.Show(result.ToString());
I know your question has been answered, and there are many ways you could look at handling this, but here is my suggestion with some explanations along the way:
private void button1_Click(object sender, EventArgs e)
{
string fullName = "Jean Claude Van Dam";
fullName = fullName.Trim();
// So we split it down into tokens, using " " as the delimiter
string[] names = fullName.Split(' ');
string strFormattedMessage = "";
// How many tokens?
int iNumTokens = names.Length;
// Iterate tokens
for(int iToken = 0; iToken < iNumTokens; iToken++)
{
// We know the token will be at least one letter
strFormattedMessage += Char.ToUpper(names[iToken][0]);
// We can't assume there is more letters (they might have used an initial)
if(names[iToken].Length > 1)
{
// Add them (make it lowercase)
strFormattedMessage += names[iToken].Substring(1).ToLower();
// Don't need to add "\n\n" for the last token
if(iToken < iNumTokens-1)
strFormattedMessage += "\n\n";
}
// Note, this does not take in to account names with hyphens or names like McDonald. They would need further examination.
}
if(strFormattedMessage != "")
{
MessageBox.Show(strFormattedMessage);
}
}
This example avoids having all of the variables. And it makes use of the operator [].
Hope this helps you too ... :)
public static string getMiddleName(string fullName)
{
var names = fullName.Split(' ');
string firstName = names[0];
string middleName = "";// names[1];
var index = 0;
foreach (var item in names)
{
if (index > 0 && names.Length -1 > index)
{
middleName += item + " ";
}
index++;
}
return middleName;
}

ambiguity in String startswith the given string

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;
}
}

How to get distinct values separately in string array?

i have two string array
string[] oldname = ["arun","jack","tom"];
string[] newname = ["jack","hardy","arun"];
here i want compare these two string arrays to get these distinct values separately like :
oldname = ["tom"];
newname = ["hardy"];
how to achieve these ...
string[] oldNameDistinct = oldname.Where(s => !newname.Contains(s)).ToArray();
string[] newNameDistinct = newname.Where(s => !oldname.Contains(s)).ToArray();
Let the two arrays were defined like the following:
string[] oldname = new[] { "arun", "jack", "tom" };
string[] newname = new string[] { "jack", "hardy", "arun" };
Then you can use the Extension method .Except to achieve the result that you are looking for. Consider the following code and the working example
var distinctInOld = oldname.Except(newname);
var distinctInNew = newname.Except(oldname);
Try this :
string[] oldname = new string[] { "arun", "jack", "tom" };
string[] newname = new string[] { "jack", "hardy", "arun" };
List<string> distinctoldname = new List<string>();
List<string> distinctnewname = new List<string>();
foreach (string txt in oldname)
{
if (Array.IndexOf(newname, txt) == -1)
distinctoldname.Add(txt);
}
foreach (string txt in newname)
{
if (Array.IndexOf(oldname, txt) == -1)
distinctnewname.Add(txt);
}
//here you can get both the arrays separately
Hope this help :)
string[] oldname = new []{"arun","jack","tom"};
string[] newname = new []{"jack","hardy","arun"};
// use linq to loop through through each list and return values not included in the other list.
var distinctOldName = oldname.Where(o => newname.All(n => n != o));
var distinctNewName = newname.Where(n => oldname.All(o => o != n));
distinctOldName.Dump(); // result is tom
distinctNewName.Dump(); // result is hardy

how to split a string array after a fixed length

I have listbox userOptions of object type giving me a result as
{ Number = 1, FName = "ABC", LName = "D" }
{ Number = 2, FName = "EFG", LName = "E" }
{ Number = 3, FName = "HIJ", LName = "F" }
{ Number = 4, FName = "ABC", LName = "G" }
and need to store in a string array just the FName information like
string[] data = new string[3];
string data[0]=ABC
string data[1]=EFG
string data[2]=HIJ
Also to remove the duplicate data from FName too;
I tried with the following code ,but it is time consuming as i cant split the string array data from FName = "ABC" to just 'ABC'
for (int i = 0; i < userOptions.Count; i++)
{
foreach (object items in userOptions)
{
devicedata = userOptions[i].ToString();
string[] Arr = devicedata .Split(',');
devdata[i] = Arr[1];
}
}
here devicedata gives me this information { Number = 1, FName = "ABC", LName = "D" }
Arr splits the data as FName = "ABC" and stores in devdata[i]
how can i merge my above two code so that i can directly get the distinct data like
string data[0]= ABC
string data[1]= EFG
string data[2]= HIJ
If you are really getting JSON (which is weird) you could also just use a regular expression for a fairly simple solution.
Ungreedy:
FName = "(.*)"
Example:
https://regex101.com/r/pCwz3r/1

Categories