简体   繁体   English

如何获取文本直到字符串中的符号

[英]How to get text until a symbol in string

How to get text before a symbol in string ? 如何在字符串中的符号前获取文本? Any ideas? 有任何想法吗?

eg acsbkjb/123kbvh/123jh/ 例如acsbkjb/123kbvh/123jh/

get text before first - "/" 首先获取文字-“ /”

尝试这个

string ss = myString.Split('/')[0];

You can use Substring() method to get the required part of the string. 您可以使用Substring()方法获取字符串的必需部分。

String text="acsbkjb/123kbvh/123jh/";
int index=text.IndexOf('/');  
String text2="";

if(index>=0)
text2=text.Substring(0,index);

得到像

youstring.Substring(0,yourstring.IndexOf('/'));

The IEnumerable approach IEnumerable方法

  string str = "acsbkjb/123kbvh/123jh/";
  var result = new string(str.TakeWhile(a => a != '/').ToArray());
  Console.WriteLine(result);

If there are no forward slashes this works without need to check the return of IndexOf 如果没有正斜杠,则无需检查IndexOf的返回即可

EDIT Keep this answer just as an example because the efficiency of this approach is really worse. 编辑保留此答案作为示例,因为这种方法的效率确实很差。 IndexOf works faster also if you add an if statement to check the return value. 如果添加if语句来检查返回值,IndexOf的工作速度也会更快。

string text = "acsbkjb/123kbvh/123jh/";    
string text2 = text.Substring(0, text.IndexOf("/"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM