如何在java字符串中的特定位置特定字符

时间:2013-10-29 08:05:10

标签: java string

我有一个包含value >00:01:00的java字符串。我需要从此字符串中删除“> ”的符号,但我无法实现此目的。

我正在使用以下代码来实现目标,

String duration = "value >00:01:00";
duration.substring(8, duration.length() - 9);

6 个答案:

答案 0 :(得分:4)

你可以做这样的事情

String duration = ">00:01:00";
duration = duration.substring(duration.indexOf('>') + 1, duration.length()); // substring from index of that char to a specific length(I've used the length as the end index)
duration = duration.substring(duration.indexOf('>') + 1); // substring from index of that char to the end of the string (@DanielBarbarian's suggestion)

从特定字符的索引获取子字符串(您需要+1,因为您需要从下一个索引获得子字符串)到String的结尾。

如果您不想提取子字符串,也可以替换该特定字符。

String duration = ">00:01:00";
duration = duration.replace(">", "");

答案 1 :(得分:4)

你也可以这样做

duration = duration.replace(">", "").trim();

答案 2 :(得分:2)

试试这个:

 String duration = ">00:01:00";
 duration = duration.replace(">","");
 System.out.println(duration);

答案 3 :(得分:2)

您可以通过以下方式进行操作:

1。 public String substring(int beginIndex,int endIndex)

String duration = ">00:01:00";
duration = duration.substring(duration.indexOf('>') + 1, duration.length());

2。 public String replace(CharSequence target,CharSequence replacement)

String duration = ">00:01:00";
duration = duration.replace('>', '');

3。使用public String substring(int beginIndex)

String duration = ">00:01:00";
duration = duration.substring(duration.indexOf('>') + 1);

4。使用public String replaceFirst(String regex,String replacement)

String duration = ">00:01:00";
duration = duration.replaceFirst(">", "");

5。使用public String replaceAll(String regex,String replacement)

String duration = ">00:01:00";
duration = duration.replaceAll(">", "");

输出

00:01:00

答案 4 :(得分:1)

duration .substring(duration.length() - 8);应删除>登录。

答案 5 :(得分:0)

 String duration = ">00:01:00";
  //Method 1
  String result = duration.replace(">", "");
  System.out.println(result);

  //Method 2
  String result2 = duration.substring(1);
  System.out.println(result2);

  //Method 3
  /***
   * Robust method but requires these imports
   * import java.util.regex.Matcher;
   * import java.util.regex.Pattern;
   */
  Pattern p = Pattern.compile("(\\d{2}:\\d{2}:\\d{2})") ;
  Matcher m = p.matcher(duration);
  if (m.find())
  { 
     String result3 = m.group(1);
     System.out.println(result3);
  }