15
Example:
I have a string "João da Maquipe", as I do to cut in space, leaving as a result: "João" or "João". whatever. In PHP I know, but in C# I have no idea.
15
Example:
I have a string "João da Maquipe", as I do to cut in space, leaving as a result: "João" or "João". whatever. In PHP I know, but in C# I have no idea.
16
The dcastro solution is good but I prefer it this way:
var parte = texto.Substring(0, texto.IndexOf(' '));
Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.
I made a comparison between the two forms and mine has making optimization very fast. The other is not only much slower in this scenario but it also consumes so much memory that I could only make 10,000 interactions before having a memory problem. Besides requiring the use of the LINQ that has its place, just not in this.
It does not mean that it is not valid and cannot be used without problems in some scenarios, but the one I posted is much simpler. And it’s closer to what’s done in other languages that AP is learning as well. It’s more readable to most people.
14
Usa String.Split
to separate the string into a collection of strings separated by a space. And then use FirstOrDefault
to obtain the first item of that collection, or null
if the collection is empty.
var first = str.Split(' ').FirstOrDefault();
Browser other questions tagged c# .net string
You are not signed in. Login or sign up in order to post.