java - 拆分字符串 ('_' 作为分隔符)

标签 java string parsing

我有以下字符串

String S1="S1_T1_VIEW";

我希望它被拆分并分配给这样的字符串:

String permission = "VIEW";
String component = "S1_T1";
String parent = "S1";

我尝试使用 S1.split() 函数,但没有太大帮助。

字符串也可以这样

String S1="S1_T1_C1_DELETE";

那个时候结果应该是

String permission = "DELETE";
String component = "S1_T1_C1";
String parent = "S1_T1";

任何建议都会有所帮助。

提前致谢

最佳答案

我假设如下:

  • permissionS1 最后一个下划线之后的部分。
  • componentS1 最后一个下划线之前的部分。
  • parentcomponentits 最后一个下划线之前的部分。

如果是这样,也许试试下面的方法?这本质上只是对上述规则的字面解释,通过找到合适的下划线来拆分字符串。

int lastUnderscore = S1.lastIndexOf("_");
String permission = S1.substring(lastUnderscore + 1);
String component = S1.substring(0, lastUnderscore);
lastUnderscore = component.lastIndexof("_");
String parent = component.substring(0, lastUnderscore);

关于java - 拆分字符串 ('_' 作为分隔符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16603425/

相关文章:

c++ - 使用 boost::spirit 解析引用字符串

Java:如何在单个定义中组合具有多个签名的方法?

java - 使用 apache-camel 在 Java 中获取 SQL 记录并使用制表符分隔分隔符写入文本文件(Spring 和 XML DSL 文件除外)

c# - 使用 SQL 身份验证处理连接字符串

excel - 按月在美国所有州的 Excel 中获得最高排名的最简单方法?

php - 需要帮助从 Div 中删除空格

java - eclipse try-with-resource 模板?

java - 验证方法被调用并中断执行/忽略以后的失败

c++ - 使用字符串替换函数用初始化变量替换字符串的一部分?

c - 如何使用 fscanf 或 fgets 在结构中动态分配字符串?