Splitting two strings and rejoining - c#

I am currently working on an address selector for a checkout process, this currently has a function that adds a comma after all fields that are found on the check out like this.
This is done using,
ddl.Items.Add(new ListItem(string.Join(", ", lines.ToArray()), address.ID.ToString()));
This is fine until you add a name in, which is a must have so they may use their account to delivery to a different person in the case of gifts or if you wish to order something and have someone else sign for the product. I wish for my first/last name to not have a comma between them, however... I can't simply do this by not adding a comma on the first two fields as there is many cases in which a name would not be entered on the delivery address.
This is how it displays currently
I was thinking the best way to do this was to split the name into a separate string and then the rest of the address into another, add the commas in and then rejoin the strings into one.
If anyone could think of a better way to do this, please share your ideas.

1 You can also use
string.Concat(lines.ToArray()).Replace(" ",",");
2 Or iterate with foreach and build stringBuilder

I have used this method,
StringBuilder fullName = new StringBuilder();
List<string> lines = new List<string>();
if (!string.IsNullOrEmpty(address.Name))
fullName.AppendFormat("{0} ", address.Name);
if (!string.IsNullOrEmpty(address.Name1))
fullName.AppendFormat("{0} ", address.Name1);
if (!string.IsNullOrEmpty(address.Name2))
fullName.Append(address.Name2);
if (!string.IsNullOrEmpty(fullName.ToString()))
lines.Add(fullName.ToString());

String = String.Replace(","," ");
or
String = String.Replace(","," ");
This will do what you want.

Related

Splitting large string in c# and adding values in it to a List

I have a string as shown below
string names = "<?startname; Max?><?startname; Alex?><?startname; Rudy?>";
is there any way I can split this string and add Max , Alex and Rudy into a separate list ?
Sure, split on two strings (all that consistently comes before, and all that consistently comes after) and specify that you want Split to remove the empties:
var r = names.Split(new[]{ "<?startname; ", "?>" }, StringSplitOptions.RemoveEmptyEntries);
If you take out the RemoveEmptyEntries it will give you a more clear idea of how the splitting is working, but in essence without it you'd get your names interspersed with array entries that are empty strings because split found a delimiter (the <?...) immediately following another (the ?>) with an empty string between the delimiters
You can read the volumes of info about this form of split here - that's a direct link to netcore3.1, you can change your version in the table of contents - this variant of Split has been available since framework2.0
You did also say "add to a separate list" - didn't see any code for that so I guess you will either be happy to proceed with r here being "a separate list" (an array actually, but probably adequately equivalent and easy to convert with LINQ's ToList() if not) or if you have another list of names (that really is a List<string>) then you can thatList.AddRange(r) it
Another Idea is to use Regex
The following regex should work :
(?<=; )(.*?)(?=\s*\?>)

c# Remove elements from List containing string [duplicate]

What would be the fastest way to check if a string contains any matches in a string array in C#? I can do it using a loop, but I think that would be too slow.
Using LINQ:
return array.Any(s => s.Equals(myString))
Granted, you might want to take culture and case into account, but that's the general idea.
Also, if equality is not what you meant by "matches", you can always you the function you need to use for "match".
I really couldn't tell you if this is absolutely the fastest way, but one of the ways I have commonly done this is:
This will check if the string contains any of the strings from the array:
string[] myStrings = { "a", "b", "c" };
string checkThis = "abc";
if (myStrings.Any(checkThis.Contains))
{
MessageBox.Show("checkThis contains a string from string array myStrings.");
}
To check if the string contains all the strings (elements) of the array, simply change myStrings.Any in the if statement to myStrings.All.
I don't know what kind of application this is, but I often need to use:
if (myStrings.Any(checkThis.ToLowerInvariant().Contains))
So if you are checking to see user input, it won't matter, whether the user enters the string in CAPITAL letters, this could easily be reversed using ToLowerInvariant().
Hope this helped!
That works fine for me:
string[] characters = new string[] { ".", ",", "'" };
bool contains = characters.Any(c => word.Contains(c));
You could combine the strings with regex or statements, and then "do it in one pass," but technically the regex would still performing a loop internally. Ultimately, looping is necessary.
If the "array" will never change (or change only infrequently), and you'll have many input strings that you're testing against it, then you could build a HashSet<string> from the array. HashSet<T>.Contains is an O(1) operation, as opposed to a loop which is O(N).
But it would take some (small) amount of time to build the HashSet. If the array will change frequently, then a loop is the only realistic way to do it.

How to save multiple strings in distinct locations and not in one string

I recently started learning about programming with C# and I have encountered a little problem with my small task that I got.
But first let me just go through a little bit what I learned so far about strings.
So, string text = Console.ReadLine(); saves whatever the user writes into that variable.
Next, I worked with a Backpack code where the user can 1. Add items in the backpack and 2. Present the items in the backpack. Here I worked with the += operator so that whenever the user added an item it would be added to the string variable.
Now I am working with a diary/blog code. The user can:
Write a new text (with a title).
Search and present the texts written.
I am stuck because I can't just have one string variable for the text that the users writes because it will be overwritten every time the user adds a new text. And I can't use += operator since I don't want to add more text to my string variable. Every time the user adds a new text it has to be saved into a new string variable (I guess?).
I just don't know how to write this code.
A good way to fix your issue is to use Classes. Maybe you can create a Blog Class with two properties Title and Body and then all you have to do is to simply create a list of Blogs.
class Blog
{
string Title {get;set;}
string Body {get;set;}
}
Each object of Blog Class represent a new post and a list of blog will give you the list of all the blog posts.
List<Blog> blogs = new List<Blog>();
You can use a generic collection like List. They are build for gathering items of one certain type. In your case it would be: List<string> allTexts. You can add strings to it with the Add method:
List<string> allTexts = new List<string>();
string newText = Console.ReadLine();
allTexts.Add(newText);
and you can access them via the [ ] operator
string textNr4 = allTexts[3];
Note: indexing starts with 0!
If you like to search for certain parts of a text you could use LINQ
string searchWord = "and";
List<string> allMatchedTextes = allTexts.Where(text=>text.Contains(searchWord)).ToList();
this will return all strings that contain the searchWord

StringReader formatted string

I have followed this Wordpress tutorial which works great. I have used a listview and when i try to format the string it doesn't recognise the \t (but does recognise \n). It also won't recognise String.Format etc.
Is there anyway that I can format the string using tabs or something similar?
Cheers
EDIT
for( i = 0; i < lstView.Items.Count;i++)
{
name = lstView.Items[i].Text;
state = lstView.Items[i].SubItems[1].Text;
country = lstView.Items[i].SubItems[2].Text;
line += name + "\t" + state + "\t" + country + "\n";
}
StringReader reader = new StringReader(line);
When line is used to print the string is joined together so the \t doesn't work. The \n for a new line does work though. Does anyone know any way that I can format the string without using spaces.
The result is like this
NameStateCountry
LongernameStateCountry
anotherNameAnotherStateAnotherCountry
Where I would like them lined up (like in a table) with name one column, state another column and country then third
Any suggestions greatly appreciated
Well, it is a bit odd that tabs are lost, but on the other hand, tabs will probably be problematic if the individual string elements (name, state etc.) varies in length.
What you could do instead is use string.Format() and use fixed column widths.
To get nice visual output this would include a parse step to determine the correct column width.
When this is done, use something like this to use spaces instead of tabs.
string line = string.Format("{0,-20}{1,-20}{2,-20}", "name", "state", "country");
EDIT: Saw that you did not want to use spaces.
In this case, you will probably need to handle this in the printing algorithm itself. You could still separate items with tabs, then for each line split it on tabs, creating an array of items (columns) per line.
For each item, print it using Graphics.DrawString() with a suitable X-position offset.
See the documentation for Graphics.DrawString.

How to separate name and surname

I have code name and surname put into same string with coma in the middle ,as "JohnSmith"
I need to insert into database to separate
Can you show me how to code that please.
Thanks
vijay
Presumably your asking how to split up a single string where the names are seperated by a comma ','
If that's the case, you can split a string using the Split(char x) method.
Then you can use each part what ever way you want.
string x = "John,Smith";
string [] parts = x.Split(',');
if(parts.Length == 2)
{
string firstName = parts[0];
string secondName = parts[1];
}
Something like that.
Vijay, how about at least trying to google stuff like this by yourself? As in "C# split string"? Hundreds of decent results come up. Heck, there are tons of these examples on SO as well.
Other people can't do your work for you, so how about actually putting in some effort into learning process instead of relying on others to do mundane things for you?
This is easy in most cases, but in a production environment the edge cases kill you. I like the string.split answer, but the incredible variation in how names are formated means more thinking and more code.

Categories