简体   繁体   English

删除开头部分字符串,最后在java中删除部分字符串

[英]Delete some part of the string in beginning and some at last in java

I want a dynamic code which will trim of some part of the String at the beginning and some part at last.我想要一个动态代码,它将在开始时修剪字符串的某些部分,最后修剪部分。 I am able to trim the last part but not able to trim the initial part of the String to a specific point completely.我能够修剪最后一部分,但无法将字符串的初始部分完全修剪到特定点。 Only the first character is deleted in the output.输出中仅删除第一个字符。

public static String removeTextAndLastBracketFromString(String string) {
  StringBuilder str = new StringBuilder(string);
  int i=0;
  do {
    str.deleteCharAt(i);
    i++;
  } while(string.equals("("));
  str.deleteCharAt(string.length() - 2);
  return str.toString();
}

This is my code.这是我的代码。 When I pass Awaiting Research(5056) as an argument, the output given is waiting Research(5056 . I want to trim the initial part of such string till ( and I want only the digits as my output. My expected output here is - 5056 . Please help.当我将Awaiting Research(5056)作为参数传递时,给出的输出是waiting Research(5056 。我想修剪此类字符串的初始部分直到 ( 并且我只想要数字作为我的输出。我的预期输出是 - 5056 。 请帮忙。

You don't need loops (in your code), you can use String.substring(int, int) in combination with String.indexOf(char) :您不需要循环(在您的代码中),您可以将String.substring(int, int)String.indexOf(char)结合使用:

public static void main(String[] args) {
    // example input
    String input = "Awaiting Research(5056)";
    // find the braces and use their indexes to get the content
    String output = input.substring(
                        input.indexOf('(') + 1, // index is exclusive, so add 1
                        input.indexOf(')')
                    );
    // print the result
    System.out.println(output);
}

Output:输出:

5056

Hint:暗示:

Only use this if you are sure the input will always contain a ( and a ) with indexOf('(') < indexOf(')') or handle IndexOutOfBoundsException s, which will occur on most String s not matching the braces constraint.仅当您确定输入将始终包含带有indexOf('(') < indexOf(')')(和 a )或处理IndexOutOfBoundsException时才使用此方法,这将在大多数不匹配大括号约束的String上发生。

If your goal is just to look one numeric value of the string, try split the string with regex for the respective numeric value and then you'll have the number separated from the string eg:如果您的目标只是查看字符串的一个数值,请尝试使用正则表达式将字符串拆分为相应的数值,然后将数字与字符串分开,例如:

 Pattern pattern = Pattern.compile("\\d+");
 Matcher matcher = pattern.matcher("somestringwithnumberlike123");
 
 if(matcher.find()) {
     System.out.println(matcher.group());
 }

Using a regexp to extract what you need is a better option :使用正则表达式来提取您需要的内容是一个更好的选择:

String test = "Awaiting Research(5056)";
Pattern p = Pattern.compile("([0-9]+)");
Matcher m = p.matcher(test);
if (m.find()) {
    System.out.println(m.group());
}

For your case, battery use regular expression to extract your interested part.对于您的情况,电池使用正则表达式来提取您感兴趣的部分。

Pattern pattern = Pattern.compile("(?<=\\().*(?=\\))");
Matcher matcher = pattern.matcher("Awaiting Research(5056)");
if(matcher.find())
{
    return matcher.group();
}

It is much easier to solve the problem eg using the String.indexOf(..) and String.substring(from,to) .解决问题要容易得多,例如使用String.indexOf(..)String.substring(from,to) But if, for some reason you want to stick to your approach, here are some hints:但是,如果出于某种原因你想坚持你的方法,这里有一些提示:

Your code does what is does because:您的代码执行的操作是因为:

  • string.equals("(") is only true if the given string is exacly "(" string.equals("(")仅在给定字符串完全是 "(" 时才为真
  • the do {code} while (condition) -loop executes code once if condition is not true -> think about using the while (condition) {code} loop instead do {code} while (condition) -loop 如果条件不成立则执行一次代码 -> 考虑改用while (condition) {code}循环
  • if you change the condition to check for the character at i, your code would remove the first, third, fifth and so on: After first execution i is 1 and char at i is now the third char of the original string (because the first has been removed already) -> think about always checking and removing charAt 0.如果您更改条件以检查 i 处的字符,您的代码将删除第一个、第三个、第五个等等:第一次执行后 i 是 1,而 i 处的 char 现在是原始字符串的第三个字符(因为第一个已被删除)-> 考虑始终检查和删除 charAt 0。

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

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