how to get words inside a string - c#

well i am working with xml but it is not important now, the problem is the next
it returns me something so
<xml>blalbalblal asfjñs
fasdf
iduser=dmengelblack; name=angel; lastname=uc;
blablal
iduser=cccarlos; name=carlos; lastname=uc;
how do i get (dmengelblack, angel, uc, carlos, uc)
i want to save every row...
remember all it is inside a string how do i get "dmengelblack", "angel", "uc" save it, everyone in a variable, and save all this in a variable too.. for example
string id="dmengelblack";
string name="angel";
string lastname="uc";
all="dmengelblack angel uc"
and i need to save the other row too, and all rows it can have
what do i know?
i know before than username it is "id="
i know before name it is "name="
i know before lastname it is "lastname="
i kwnow everyone finish with ";"

Simple way in java is to read the file as a stream, iterate through that and get the substring between
iduser= and ;
and
name= and ;
and
lastname= and ;
EDIT: With this code you will get the list of all the filed you want as
OUTPUT:
[iduser=dmengelblack, iduser=cccarlos]
[name=angel, name=carlos]
[lastname=uc, lastname=uc]
So now you interate through these list, split the each entry on =, you will the value you wanted at the second index on split.
CODE:
String str = "<xml>blalbalblal asfjñs" + "fasdf"
+ "iduser=dmengelblack; name=angel; lastname=uc;"
+ "blablal"
+ "iduser=cccarlos; name=carlos; lastname=uc;";
List<String> iduser = new ArrayList<String>();
List<String> name = new ArrayList<String>();
List<String> lastname = new ArrayList<String>();
int i = 1;
while(str.indexOf("iduser=", i) > 0) {
i=str.indexOf("iduser=",i);
iduser.add(str.substring(i, str.indexOf(";", i)));
name.add(str.substring(str.indexOf("name=", i), str.indexOf(";", str.indexOf("name=", i))));
lastname.add(str.substring(str.indexOf("lastname=", i), str.indexOf(";", str.indexOf("lastname=", i))));
i=str.indexOf("lastname=",i);
}
System.out.println(iduser);
System.out.println(name);
System.out.println(lastname);
hope this helps.

I would use RegEx to extract the pattern of key values into a hast table (dictionary), then use a know key mapping to assign it to the variables you have (iteration with a switch statement or something)

In c# (and other languages, but they will have different syntax) you can split a string into an array of strings like this:
string myString = "item1;item2;item3";
string[] separateStrings = myString.Split(';');
This will give you a string array like:
string[0] = "item1";
string[1] = "item2";
string[2] = "item3";
I would also suggest you clean up you tags to only tag what you really care about.

Related

How to suggest new computer domain name

I'm trying to write a program that search our domain by entered name of groups of computers (for example for IT users computer name beginns with DITXX, where XX is number of computer) and suggest new computer name. For example we have computers:
DIT01
DIT02
..
DIT10
DIT11
..
DIT156
I have TextBox where i enter group name, then i get a list of computers containing this name and i'm putting them to List and to Array. But how to get last used name and suggest new (here program should suggest name DIT157 beacuse of last name DIT156)? Should i use natural sort? Or trim name DIT to have only numbers, sort them and then just find last, add 1 and then show trimmed name + this number?
Code fragments:
string name = textBox1.Text;
DirectoryEntry domain = new DirectoryEntry("LDAP://*****.****.**.**");
DirectorySearcher search = new DirectorySearcher(domain);
search.Filter = ("(&(ObjectCategory=computer)(cn=") + name + ("*))");
List<string> temp = new List<string>();
richTextBox1.Text = "";
List<string> ComputerList = new List<string>();
foreach (SearchResult c in search.FindAll())
{
var tmp = (c.GetDirectoryEntry().Name.ToString());
richTextBox1.Text = richTextBox1.Text + (tmp.Replace("CN=", "")) + (Environment.NewLine);
//listView1.Items.Add(tmp.Replace("CN=", ""),2);
temp.Add (tmp.Replace("CN=", ""));
ComputerList.Add(tmp.Replace("CN=", ""));
}
ComputerList.Sort((x, y) =>
{
int ix, iy;
return int.TryParse(x, out ix) && int.TryParse(y, out iy)
? ix.CompareTo(iy) : string.Compare(x, y);
});
string[] Computers = ComputerList.ToArray();
Array.Sort(Computers);
foreach (var item in Computers)
{
listView1.Items.Add(item);
Console.WriteLine(item.ToString());
}
For random computer name generation I personally would try something other than query/sort, like use Random. Or perhaps append the result of Path.GetRandomFileName() to your prefix (strip out the '.') and limit the total length to 15.
If you choose to do the query and sort I would strip off the text and sort by the number alone, because your example computer names have different lengths. Sorting by string would cause DIT11 and DIT110 to be next to each other in the list. And if you write a sorting algorithm you will end up stripping off the text anyway.

In C # how to pass string.empty in a list of string

i have a list of string
Emails = new List<string>() { "R.Dun#domain.co.nz", "S.Dun#domain.co.nz" }
now i want to pass string.empty to first value of list
something like
policy.Emails = new List<string>(){string.Empty};
how to put a loop for e.g. for each value of list do something.
you can directly set the first element as string.Empty:
policy.Emails[0]=string.Empty;
You can use indexof function for finding a string in the list as below,
List<string> strList = new List<string>() { "R.Dun#domain.co.nz", "S.Dun#domain.co.nz" };
int fIndex = strList.IndexOf("R.Dun#domain.co.nz");
if(fIndex != -1)
strList[fIndex] = string.Empty;
Or if you want to replace first item with string.Empty then as dasblinkenlight mentioned you can do using the index directly,
strList[0] = string.Empty
Hope it helps.
You can prepend string.Empty to an existing list with concat:
var emails = new List<string> {"R.Dun#domain.co.nz", "S.Dun#domain.co.nz"};
policy.Emails = new[] {string.Empty}.Concat(emails).ToList();
Now policy.Emails looks like this:
{"", "R.Dun#domain.co.nz", "S.Dun#domain.co.nz"}
If you would like to replace the first item, use Skip(1) before concatenating:
policy.Emails = new[] {string.Empty}.Concat(emails.Skip(1)).ToList();
To generalize, replacing the initial n values with empty strings would look like this:
policy.Emails = Enumerable.Repeat(string.Empty, 1).Concat(emails.Skip(n)).ToList();
Note: It goes without saying that if you do not mind modifying the list in place, the simplest solution is to do
emails[0] = string.Empty;
If you want to add an empty string at the beginning of a list you could do:
emails.Insert(0, string.Empty);

How to remove a specific string from list<strings>

I've got a list of strings called xyz the string has this structure iii//abcd, iii//efg. how can I loop through this list and remove only iii// ?
I have tried this but it remove everything. thanks
string mystring = "iii//";
xyz.RemoveAll(x=> x.Split ('//')[0].ToString().Equals (mystring));
Removing all the strings who start with iii//:
xyz.RemoveAll(x => x.StartsWith(#"iii//"));
Removing the iii// from all strings:
var newList = xyz.Select(x => x.Replace(#"iii//", string.Empty)).ToList();
You can try this also which will remove the string from list if it starts with "iii/" other wise not.
string mystring = "iii//";
xyz.RemoveAll(x=>x.StartsWith(mystring));
I believe OP wants something to remove iii// from all strings:
string prefix = "iii///";
List<string> xyz = ...;
var result = xyz.Select(x => x.Substring(prefix.Length)).ToList();
Note: this of course assumes that each string really starts with prefix.

How to split a server address and store in a list

I have a List<string> with some 10 strings.
The values are as follows:
\\Server\Site\MySite\File1.xml
\\Server\Site\MySite\File2.xml
\\Server\Site\MySite\File2.xml
.......................
\\Server\Site\MySite\File10.xml
I need to extract \MySIte\File1.xml to \MySite\File10.xml and store in another list.
I tried to use Split keyword, with another list to populate the splitted string. But it doesn't seem to give the correct answer.
Below is the code:
for(int index=0;index<list.Count;list++)
{
string[] myArray=list[index].Split('\\');
for(int innerIndex=0;innerIndex<myArray.Length;innerIndex++)
{
anotherList[innerIndex]=myArray[2]+"\\"+myArray[3];
}
}
Experts please help.
You don't need to work too hard if you know the input of all the strings
str.Substring(str.IndexOf("\\MySite"))
One word: LINQ!
var results = (from x in source
let parts = x.Split('\\')
select String.Join("\\", parts.Skip(1)).ToArray();
You can use following code.
List<string> source = new List<string>();
source.Add(#"\\Server\Site\MySite\File1.xml");
source.Add(#"\\Server\Site\MySite\File2.xml");
source.Add(#"\\Server\Site\MySite\File2.xml");
source.Add(#"\\Server\Site\MySite\File10.xml");
foreach(string s in source)
{
string[] parts = s.Split(new string[]{ Path.DirectorySeparatorChar.ToString() },StringSplitOptions.RemoveEmptyEntries);
Console.WriteLine(parts[parts.Length - 1] + Path.DirectorySeparatorChar +
parts[parts.Length - 2]);
}
I would just remove anything before \MySite and get the rest:
Test data used:
List<string> source = new List<string>
{
#"\\Server\Site\MySite\File1.xml",
#"\\Server\Site\MySite\File2.xml",
#"\\Server\Site\MySite\File2.xml",
#"\\Server\Site\MySite\File10.xml",
};
query:
var result =
source
// Start removing at 0 and remove everything before '\MySite'
.Select(x => x.Remove(0, x.IndexOf("\\MySite")))
.ToList();

Can I select individual Items from a list?

I have a list of strings and I need to select certain parts of the list to construct a separate string. What I have is:
name,gender,haircolour,car;
or
John,Male,Brown,toyota;
I also have a separate file indicating which parts, and in what order the new string should be constructed.
eg: Index = 0,3,1 would print John,toyota,Male or 1,2,0 would print Male,Brown,John.
I have tried several methods to try and select the index of the items I want, but all the functions that return values only return the contents of the List, and the only return that gives an integer is Count(), which I can't see as being helpful.
I have tried and tried but all I have succeeded in doing is confusing myself more and more. Can anyone help suggest a way to achieve this?
You should be able to do list[i], where i is the index of the element you need. There are some examples here: http://www.dotnetperls.com/list
List<string> list = new List<string> { "John", "Male", "Brown", "toyota" };
List<int> indexList = new List<int> { 0, 3, 1 };
List<string> resultList = new List<string>();
indexList.ForEach(i => resultList.Add(list[i]));
If I am understanding the question correctly, something like this should do the job:
const string data = "John,Male,Brown,toyota";
const string order = "0,3,1";
string[] indexes = order.Split(',');
string result = indexes.Aggregate("", (current, index) => current + data.Split(',')[int.Parse(index)] + ",");
result = result.TrimEnd(',');
If your string data ends with a semicolon ';', as possibly indicated in your question, then change the line to this:
string result = indexes.Aggregate("", (current, index) => current + data.Split(',')[int.Parse(index)].TrimEnd(';') + ",");
Note this solution doesn't check to make sure that the given index exists in the given data string. To add a check to make sure the index doesn't go over the array bounds, do something like this instead:
string result = indexes.Where(z => int.Parse(z) < data.Split(',').Length).Aggregate("", (current, index) => current + data.Split(',')[int.Parse(index)].TrimEnd(';') + ",");

Categories