简体   繁体   English

如何删除字符串的一部分?

[英]How to delete a part of a string?

For example, if I have multiple strings of the type something, $other and I'd like to delete the part after the comma, so that I get something how can I do it? 举例来说,如果我有种类多串something, $other ,我想逗号后删除的部分,所以我得到something我该怎么办呢? I remember that there was a way to do it using % or something but I can't find it. 我记得有一种方法可以使用%或其他方式来实现,但是我找不到它。

you could use string split to accomplish what you want 您可以使用字符串拆分来完成所需的操作

String s = "something, $other";
String whatYouWant = s.split(",")[0];

Take a look at the String api. 看一下String api。 You can get the index "something, $something".indexOf() of the comma. 您可以获取逗号的索引“ something,$ something” .indexOf()。 Then use that index and the substring() method. 然后使用该索引和substring()方法。

A version without using .split() and thus without iterating the entire string. 不使用.split()且因此不迭代整个字符串的版本。

Using substring : 使用substring

String s = "something, $other";
String whatYouWant = s.substring( 0, s.indexOf(","));

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

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