有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

解析字符串java get index

我有很多这种类型的变量字符串

  String 1 = s3345 section sector ground
  String 2=  s35 section sector ground
  String 3=  s99983 section sector ground

我只需要取s的值,但这个值不是固定的,而是可变的。 如何找到s的最终索引


共 (2) 个答案

  1. # 1 楼答案

    假设您想要获取s3345等的数值,并且该部分可以位于字符串中的任何位置,请尝试使用正则表达式替换该值:

    String input = "s3345 section sector ground";
    String number = input.replace(".*\\bs(\\d+)\\b.*", "$1"); //number would be "3345"
    

    如果您的输入字符串是固定的,即它总是s<value> section sector <name>,那么您可以将其添加到正则表达式中,使其更严格

  2. # 2 楼答案

    假设数字总是在开始时出现

     String s = "s3345 section sector ground";
     System.out.println((s.split(" "))[0]); //check has to be applied for empty string.