Home > Computer Tutorials > Computer Knowledge > Java method to extract string prefix

Java method to extract string prefix

PHPz
Release: 2024-01-16 11:42:19
forward
529 people have browsed it

Java method to extract string prefix

Help write a java method to extract the first participle of String

public class SubString {

//Class for processing strings

public static String getString(String src, String target) {

//Get the content before the last occurrence of target in the source string src

return src.substring(0, src.lastIndexOf(target));

}

//For testing

public static void main(String[] args) {

// TODO Auto-generated method stub

String target = "Department"; //Set target to "Department"

//Get the required string

String result = getString("Commissary", target); //For the sake of harmony..

System.err.println(result);

}

}

Output result:

小selling

This method is also applicable to multiple words, such as management department. When the target is set to "department", the running result of the program will be "management"

How does Java use regular expressions to complete the following tasks: truncate strings starting with letters or numbers

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class ttts {

public static void main(String... strs) {

String str = "VVV4BC3233BBB";

System.out.println(getStrings(new StringBuilder(),str));

}

public static String getStrings(StringBuilder sb,String str) {

if (str == null)return """;

if (str.equals("""))return sb.toString();

Pattern p = Pattern.compile("[a-zA-Z]*[0-9]*");

Matcher m = p.matcher(str);

if (m.find()) {

String group = m.group();

sb.append(group);

String subStr = str.substring(group.length());

Pattern pattern = Pattern.compile(".*\\d .*");

if (pattern.matcher(subStr).matches()) {

getStrings(sb,str.substring(group.length()));

}

}

return sb.toString();

}

}

The above is the detailed content of Java method to extract string prefix. For more information, please follow other related articles on the PHP Chinese website!

source:docexcel.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template