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
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);
}
}
}
example of the column
I have a column called FULLNAME which consists of a variation of FIRSTNAME and SURNAME separated by a space, and TITLE, FIRSTNAME and SURNAME, all separated by a space. So for example, I could have JOHN SMITH or DR JOHN SMITH.
I am using C# in Visual Studios.
I loop through each of these as per:
foreach (DataRow dr in spreadsheetdata.Tables["EPABase"].Rows)
And my array for the title is as:
title[0] = "Mr";
title[1] = "Mrs";
title[2] = "Miss";
title[3] = "Ms";
title[4] = "Dr";
title[5] = "Rev";
title[6] = "Hon";
title[7] = "Mx";
title[8] = "Other";
It doesn't matter which way around I work, but it's probably easier to get the SURNAME first because it'll always be the the last set of characters in a string, up to the first space value from the right. If I an get this into it's own string of SURNAME, then remove it from the original FULLNAME string, I can then use my array to see if the first set of characters from the left up to the first space appears in it, and if so use as the TITLE string, but if not, use the remaining string after the deletion of the SURNAME to be the FIRSTNAME string.
Just a bit stuck as to how to achieve the first step of this, getting the SURNAME out. I have tried LASTINDEXOF, but this is an integer value, and I need string.
If you are sure that First name or Last Name don't have space in it, you try something like this:
string[] fullNames = { "John Smith", "Dr John Smith" };
string[] titles = { "Mr", "Mrs", "Dr" };
foreach (var item in fullNames)
{
var details = item.Split(' ');
if (titles.Contains(details[0]))
{
Console.WriteLine($"Title: { details[0]} ");
Console.WriteLine($"First Name: { details[1]} ");
Console.WriteLine($"Last Name: { details[2]} ");
}
else
{
Console.WriteLine($"First Name: { details[0]} ");
Console.WriteLine($"Last Name: { details[1]} ");
}
}
To get the surname you can do something as follows:
foreach (DataRow dr in spreadsheetdata.Tables["EPABase"].Rows)
{
var value = dr["FULLNAME"].ToString();
var elementsOfName = value.Split(" ");
var lastName = elementsOfName[elementsOfName.Length - 1];
Console.WriteLine(lastName);
}
how can I get the remaining text/values of ImageString and return it in a variable? In my current code below i got an error.
Note: ImageString = data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAOEAlgDASIAAhEBAxEB/8QAHQABAAICAwEBAAAAAAAAAAAAAAUGAwQBAgcICf/EAEkQAQABAwMCAgcCDAMFBgcAAAABAgMEBREhMTIGEgciQVFhcYETkQgUIzNCUnKCobHB0RVikkNjc7LwFhckNKL
var _strings= { response = "True", name = "John", ImageString = "(random text here (1-1000 of characters maybe?))"};
var _split = _strings.Substring(_strings.IndexOf("ImageString"), _strings.Length);
"Index and length must refer to a location within the string.
Expected Out : I want to get all the text from the "ImageString"
In your particular case you can use JSON serializer:
public class Data
{
public string ImageString { get; set; }
}
var data = Newtonsoft.Json.JsonConvert.Deserialize<Data>(_strings);
var myImageString = data.ImageString;
var _strings= { response = "True", name = "John", ImageString = "(random text here (1-1000 of characters maybe?))"};
The above looks like an anonymous object but i am assumming you mean the structure of your text by it.
var imageStringIndex= _strings.IndexOf("ImageString");
var _split = _strings.Substring(imageStringIndex<0?0:imageStringIndex, _strings.Length - 1);
or
var _split = _strings.Split("ImageString".ToCharArray()).Last();
both you work for your case
If I've understood you right, and you insist on string manipulations (not Json parsing)
string _strings =
"{ response = \"True\", name = \"John\", ImageString = \"bla-bla-bla\" };";
string toFind = "ImageString";
int p = _strings.IndexOf(toFind);
// bla-bla-bla
string remain = p < 0
? "" //TODO: Not found at all (shall we return an empty or entire string?)
: _strings
.Substring(p + toFind.Length)
.TrimStart(' ', '=') // to be on the safe side: what if data starts from =
.TrimStart('"', ' ')
.TrimEnd('}', ';', ' ')
.TrimEnd('"', ' ');
First problem I'm seeing is that
var _strings= { response = "True", name = "John", ImageString = "(random text here (1-1000 of characters maybe?))"};
Is not a string, rather an attempt at an anonymous object?
If it is, you can declare the object using:
var _strings = new { response = "True", name = "John", ImageString = "(random text here (1-1000 of characters maybe?))" };
Then access any property in the object using standard c# syntax:
var imageString = _strings.ImageString;
The answer to your question depends very much on where the information is coming from as you can declare it and manipulate it in a thousand different ways if you have control over it.
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");
}
I am trying to split a string to get json object value - I have text values with numerous lines in the format:
new Car() { Id = 1, Year = 1926, Make = "Chrysler", Model = "Imperial", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRPe4CygIW-MuZL5jl77wlgXXK5_ANyC9l1X4QqLizCOkaVAlRe","image_url":"http://imperialclub.org/Yr/1926/photos/Phaeton2Big.jpg","width":1632,"height":1032}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },
new Car() { Id = 2, Year = 1950, Make = "Hillman", Model = "Minx Magnificent", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcScVsGEeRBh6xZYXr6Gm35Sk5ecSlk_ax3qZmoGRAtBbZC8vJZ9","image_url":"http://i.ebayimg.com/images/g/gcIAAOSwKadXPeLs/s-l300.jpg","width":300,"height":225}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },
new Car() { Id = 3, Year = 1954, Make = "Chevrolet", Model = "Corvette", ImageUrl = "{"data":{"images":[{"thumb_url":"https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSdZntu4tgWrZrxwqeuKlteCP9vJGnqUlmNq5JF1bBCf-EJy5r8","image_url":"http://momentcar.com/images/chevrolet-corvette-1954-1.jpg","width":1000,"height":600}]},"error_code":0,"error":false,"message":"1 images(s) available"}" },
What I would really like is to get them in the format:
new Car() { Id = 1, Year = 1926, Make = "Chrysler", Model = "Imperial", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcRPe4CygIW-MuZL5jl77wlgXXK5_ANyC9l1X4QqLizCOkaVAlRe" },
new Car() { Id = 2, Year = 1950, Make = "Hillman", Model = "Minx Magnificent", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcScVsGEeRBh6xZYXr6Gm35Sk5ecSlk_ax3qZmoGRAtBbZC8vJZ9" },
new Car() { Id = 3, Year = 1954, Make = "Chevrolet", Model = "Corvette", ImageUrl = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSdZntu4tgWrZrxwqeuKlteCP9vJGnqUlmNq5JF1bBCf-EJy5r8" },
I know I can use JObject.Parse(data); to parse the json value - but just tring to get to it is becoming a bit of a nightmare. Is there a better way of doing this?
What I have so far:
static void Main(string[] args)
{
using (StreamWriter writer = new StreamWriter(#"c:\Data\temp\output.txt")) // file to write to
{
using (StreamReader reader = new StreamReader(#"c:\Data\temp\test.txt")) //file to read from
{
string line;
while (reader.ReadLine() != null)
{
line = reader.ReadLine();
string[] words = JsonSplitString(line);
string json = words[1];
writer.WriteLine("{0}", json);
}
}
}
}
static string[] JsonSplitString(string data)
{
return data.Split(new string[] { "ImageUrl" }, StringSplitOptions.None);
}
However I am getting a NullReferenceException - even though a string is being passed in to the JsonSplitString method.
You are calling reader.Readline() twice: once for the comparison and then again inside your loop. You are actually skipping every other line. And what is probably happening is that you are reaching the end of your file and then calling reader.Readline() again, which is null. Try this instead:
line = reader.ReadLine();
while (line != null)
{
string[] words = JsonSplitString(line);
string json = words[1];
writer.WriteLine("{0}", json);
line = reader.ReadLine();
}
using System;
using Newtonsoft.Json.Linq;
namespace JsonExperiments
{
class Program
{
static void Main(string[] args)
{
ExecuteEmployeeSearch();
Console.ReadLine();
}
static void ExecuteEmployeeSearch()
{
// mockup JSON that would be returned from API
string sampleJson = "{\"results\":[" +
"{\"employeename\":\"name1\",\"employeesupervisor\":\"supervisor1\"}," +
"{\"employeename\":\"name2\",\"employeesupervisor\":\"supervisor1\"}," +
"{\"employeename\":\"name3\",\"employeesupervisor\":[\"supervisor1\",\"supervisor2\"]}" +
"]}";
// Parse JSON into dynamic object, convenient!
JObject results = JObject.Parse(sampleJson);
// Process each employee
foreach (var result in results["results"])
{
// this can be a string or null
string employeeName = (string)result["employeename"];
// this can be a string or array, how can we tell which it is
JToken supervisor = result["employeesupervisor"];
string supervisorName = "";
if (supervisor is JValue)
{
supervisorName = (string)supervisor;
}
else if (supervisor is JArray)
{
// can pick one, or flatten array to a string
supervisorName = (string)((JArray)supervisor).First;
}
Console.WriteLine("Employee: {0}, Supervisor: {1}", employeeName, supervisorName);
}
}
}
}