如何使用C#从字符串中拆分和修剪几个字符 [英] How to split and trim few characters from a string using C#

查看:99
本文介绍了如何使用C#从字符串中拆分和修剪几个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,



如何使用C#从字符串中拆分和修剪几个字符,例如



string = UserName:tghgd bhbj bhbh hb



现在我想在':'之后拆分字符并修剪这些值,这样我的最终输出应该是。



字符串=用户名



请帮我这样做。

谢谢提前。

Hello,

How to split and trim few characters from a string using C# for example

string = UserName: tghgd bhbj bhbh hb

Now i want to split the characters after ':' and trim those values so my final out put should be.

String = UserName

Kindly help me to do this.
Thanks in Advance.

推荐答案

试试这个:

Try this:
string name = "UserName: tghgd bhbj bhbh hb";
name = name.Split(':').FirstOrDefault();


尝试

Try
var myStr = "string = UserName: tghgd bhbj bhbh hb";
var cln = myStr.IndexOf(":");
var output = myStr.SubString(0,cln);


完全不合适,你留下了重要的问题点,你需要判断它是你想要的第一个元素,还是最后一个或用户名本身等等。



但是,让我来看几个例子,如果它是你想要的第一个元素,那么下面的代码就足够了。



That totally doesn't fit through, you left the important points of questions, you need to tell whether it is the first element you want, or the last or the username itself and so on.

But, let me go through a few examples, if it is the first element you want in your string, then the following code would be enough.

string completeStr = "UserName: tghgd bhbj bhbh hb";

// Split and select the first element in the array string[]
// 1. Split would get a character, upon which to split the string 
// 2. We use an indexer to select an element at some index; here it is first element
string firstElement = completeStr.Split(':')[0];

// For trimming..
string trimmedStr = firstElement.Trim();





您可以阅读MSDN文档以便学习有关这些功能的更多信息,以及它们在您的应用程序中的用法。您将在那里找到这些方法的良好代码示例,以及开发人员对这些函数的一些评论。



https://msdn.microsoft.com/en-us/library/system.string.split%28v=vs.110%29.aspx [ ^ ]包含所有重载分割功能的方法。

https://msdn.microsoft。 com / zh-CN / library / t97s7bs3%28v = vs.110%29.aspx [ ^ ]修剪功能。

https://msdn.microsoft.com/en-us/library/ 2549tw02.aspx [ ^ ]可能有助于阅读索引器。



You can read the MSDN documentations to learn more about these functions, and how are they used in your application. You will find good code examples of these methods there, and some remarks from the developers about these functions.

https://msdn.microsoft.com/en-us/library/system.string.split%28v=vs.110%29.aspx[^] Contains all of the overloaded methods for Split function.
https://msdn.microsoft.com/en-us/library/t97s7bs3%28v=vs.110%29.aspx[^] Trim function.
https://msdn.microsoft.com/en-us/library/2549tw02.aspx[^] Might be helpful to read for indexers.


这篇关于如何使用C#从字符串中拆分和修剪几个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆