繁体   English   中英

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

[英]How to particular character at specific location in java string

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

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

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

你可以做这样的事情

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(">", "");

你也可以这样

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

尝试这个:

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

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

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

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

2.公共字符串替换(CharSequence目标,CharSequence替换)

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

3.使用公共字符串子字符串(int beginIndex)

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

4.使用公共字符串replaceFirst(字符串正则表达式,字符串替换)

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

5.使用公共String replaceAll(字符串正则表达式,字符串替换)

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

输出值

00:01:00

duration .substring(duration.length() - 8); 应删除>符号。

 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);
  }

暂无
暂无

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

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