Delete everything after part of a string - java

I have a string that is built out of three parts. The word I want the string to be (changes), a seperating part (doesn't change) and the last part which changes. I want to delete the seperating part and the ending part. The seperating part is " - " so what I'm wondering is if theres a way to delete everything after a certaint part of the string.
An example of this scenario would be if I wanted to turn this: "Stack Overflow - A place to ask stuff" into this: "Stack Overflow". Any help is appreciated!

For example, you could do:
String result = input.split("-")[0];
or
String result = input.substring(0, input.indexOf("-"));
(and add relevant error handling)

The apache commons StringUtils provide a substringBefore method
StringUtils.substringBefore("Stack Overflow - A place to ask stuff", " - ")

Kotlin Solution
Use the built-in Kotlin substringBefore function (Documentation):
var string = "So much text - no - more"
string = string.substringBefore(" - ") // "So much text"
It also has an optional second param, which is the return value if the delimiter is not found. The default value is the original string
string.substringBefore(" - ", "fail") // "So much text"
string.substringBefore(" -- ", "fail") // "fail"
string.substringBefore(" -- ") // "So much text - no - more"

You can use this
String mysourcestring = "developer is - development";
String substring = mysourcestring.substring(0,mysourcestring.indexOf("-"));
it would be written "developer is -"

Perhaps thats what you are looking for:
String str="Stack Overflow - A place to ask stuff";
String newStr = str.substring(0, str.indexOf("-"));

I created Sample program for all the approches and SubString seems to be fastest one.
Using builder : 54
Using Split : 252
Using Substring : 10
Below is the sample program code
for (int count = 0; count < 1000; count++) {
// For JIT
}
long start = System.nanoTime();
//Builder
StringBuilder builder = new StringBuilder(
"Stack Overflow - A place to ask stuff");
builder.delete(builder.indexOf("-"), builder.length());
System.out.println("Using builder : " + (System.nanoTime() - start)
/ 1000);
start = System.nanoTime();
//Split
String string = "Stack Overflow - A place to ask stuff";
string.split("-");
System.out.println("Using Split : " + (System.nanoTime() - start)
/ 1000);
//SubString
start = System.nanoTime();
String string1 = "Stack Overflow - A place to ask stuff";
string1.substring(0, string1.indexOf("-"));
System.out.println("Using Substring : " + (System.nanoTime() - start)
/ 1000);
return null;

Clean way to safely remove until a string, and keep the searched part if token may or may not exist.
String input = "Stack Overflow - A place to ask stuff";
String token = " - ";
String result = input.contains(token)
? token + StringUtils.substringBefore(string, token)
: input;
// Returns "Stack Overflow - "
Apache StringUtils functions are null-, empty-, and no match- safe

This will do what you need:
newValue = oldValue.substring(0, oldValue.indexOf("-");

String line = "deltaasm:/u01/app/oracle/product/11.2.0/dbhome_1:N # line addred by agent";
String rep = "deltaasm:";
String after = "";
String pre = ":N";
String aft = "";
String result = line.replaceAll(rep, after);
String finalresult = result.replaceAll(pre, aft);
System.out.println("Result***************" + finalresult);
String str = "deltaasm:/u01/app/oracle/product/11.2.0/dbhome_1:N # line addred by agent";
String newStr = str.substring(0, str.indexOf("#"));
System.out.println("======" + newStr);

you can my utils method this action..
public static String makeTwoPart(String data, String cutAfterThisWord){
String result = "";
String val1 = data.substring(0, data.indexOf(cutAfterThisWord));
String va12 = data.substring(val1.length(), data.length());
String secondWord = va12.replace(cutAfterThisWord, "");
Log.d("VAL_2", secondWord);
String firstWord = data.replace(secondWord, "");
Log.d("VAL_1", firstWord);
result = firstWord + "\n" + secondWord;
return result;
}`

Related

How to fetch a string out of "08-1_2-4_1517614" ie "1517614"

If i have string like 08-1_2-4_1517614 and if i need to fetch the value "1517614" out of this for string manipulation in java
Any help will be much appreciated
String test = " 08-1_2-4_1517614";
String [] tokens = test.split("_");
System.out.println(tokens[tokens.length - 1]);
Or with regex:
String test = " 08-1_2-4_1517614";
System.out.println(test.replaceFirst(".+_", ""));
Or:
System.out.println(test.substring(test.lastIndexOf("_") + 1));
Here is a regex replace option:
String input = "08-1_2-4_1517614";
String output = input.replaceAll("^.*_", "");
A more general regex replace option using a capture group:
String output = input.replaceAll(".*(?<!\\d)(\\d+)$", "$1");
Or we could take a substring:
String output = input.substring(input.lastIndexOf("_") + 1);
Is the pattern always the same?
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#substring-int-int- could be your friend.
"08-1_2-4_1517614".substring(9, "08-1_2-4_1517614".length()) e.g.
Best way to do it, in case you want to resuse other parts of the original String.
String num = "08-1_2-4_1517614";
String[] parts = num.split("_");
String value = parts[parts.length - 1];
System.out.println(value);
The most simple is to use regex to find all the numbers after the final underscore.
Pattern patt = Pattern.compile("[^_]+$");
Matcher matcher = patt.matcher("08-1_2-4_1517614");
if(matcher.find()) {
System.out.println(matcher.group());
}else{
System.out.println("No Match Found");
}
Or use
str.substring(str.lastIndexOf("_") + 1, str.length())
I'd go for the one-liner:
System.out.println(myString.substring(9, 16));

String Manipulation in java 1.6

String can be like below. Using java1.6
String example = "<number>;<name-value>;<name-value>";
String abc = "+17005554141;qwq=1234;ddd=ewew;otg=383";
String abc = "+17005554141;qwq=123454";
String abc = "+17005554141";
I want to remove qwq=1234 if present from String. qwq is fixed and its value can VARY like for ex 1234 or 12345 etc
expected result :
String abc = "+17005554141;ddd=ewew;otg=383";
String abc = "+17005554141"; \\removed ;qwq=123454
String abc = "+17005554141";
I tried through
abc = abc.replaceAll(";qwq=.*;", "");
but not working.
I came up with this qwq=\d*\;? and it works. It matches for 0 or more decimals after qwq=. It also has an optional parameter ; since your example seems to include that this is not always appended after the number.
I know the question is not about javascript, but here's an example where you can see the regex working:
const regex = /qwq=\d*\;?/g;
var items = ["+17005554141;qwq=123454",
"+17005554141",
"+17005554141;qwq=1234;ddd=ewew;otg=383"];
for(let i = 0; i < items.length; i++) {
console.log("Item before replace: " + items[i]);
console.log("Item after replace: " + items[i].replace(regex, "") + "\n\n");
}
You can use regex for removing that kind of string like this. Use this code,
String example = "+17005554141;qwq=1234;ddd=ewew;otg=383";
System.out.println("Before: " + example);
System.out.println("After: " + example.replaceAll("qwq=\\d+;?", ""));
This gives following output,
Before: +17005554141;qwq=1234;ddd=ewew;otg=383
After: +17005554141;ddd=ewew;otg=383
.* applies to multi-characters, not limited to digits. Use something that applies only to bunch of digits
abc.replaceAll(";qwq=\\d+", "")
^^
Any Number
please try
abc = abc.replaceAll("qwq=[0-9]*;", "");
If you don't care about too much convenience, you can achieve this by just plain simple String operations (indexOf, replace and substring). This is maybe the most legacy way to do this:
private static String replaceQWQ(String target)
{
if (target.indexOf("qwq=") != -1) {
if (target.indexOf(';', target.indexOf("qwq=")) != -1) {
String replace =
target.substring(target.indexOf("qwq="), target.indexOf(';', target.indexOf("qwq=")) + 1);
target = target.replace(replace, "");
} else {
target = target.substring(0, target.indexOf("qwq=") - 1);
}
}
return target;
}
Small test:
String abc = "+17005554141;qwq=1234;ddd=ewew;otg=383";
String def = "+17005554141;qwq=1234";
System.out.println(replaceQWQ(abc));
System.out.println(replaceQWQ(def));
outputs:
+17005554141;ddd=ewew;otg=383
+17005554141
Another one:
abc.replaceAll(";qwq=[^;]*;", ";");
You must to use groups in replaceAll method.
Here is an example:
abc.replaceAll("(.*;)(qwq=\\d*;)(.*)", "$1$3");
More about groups you can find on: http://www.vogella.com/tutorials/JavaRegularExpressions/article.html

Replace the words in String without using String replace

Is there any solution on how to replace words in string without using String replace?
As you all can see this is like hard coded it. Is there any method to make it dynamically? I heard that there is some library file able to make it dynamically but I am not very sure.
Any expert out there able to give me some solutions? Thank you so much and have a nice day.
for (int i = 0; i < results.size(); ++i) {
// To remove the unwanted words in the query
test = results.toString();
String testresults = test.replace("numFound=2,start=0,docs=[","");
testresults = testresults.replace("numFound=1,start=0,docs=[","");
testresults = testresults.replace("{","");
testresults = testresults.replace("SolrDocument","");
testresults = testresults.replace("numFound=4,start=0,docs=[","");
testresults = testresults.replace("SolrDocument{", "");
testresults = testresults.replace("content=[", "");
testresults = testresults.replace("id=", "");
testresults = testresults.replace("]}]}", "");
testresults = testresults.replace("]}", "");
testresults = testresults.replace("}", "");
In this case, you will need learn regular expression and a built-in String function String.replaceAll() to capture all possible unwanted words.
For example:
test.replaceAll("SolrDocument|id=|content=\\[", "");
Simply create and use a custom String.replace() method which happens to use the String.replace() method within it:
public static String customReplace(String inputString, String replaceWith, String... stringsToReplace) {
if (inputString.equals("")) { return replaceWith; }
if (stringsToReplace.length == 0) { return inputString; }
for (int i = 0; i < stringsToReplace.length; i++) {
inputString = inputString.replace(stringsToReplace[i], replaceWith);
}
return inputString;
}
In the example method above you can supply as many strings as you like to be replaced within the stringsToReplace parameter as long as they are delimited with a comma (,). They will all be replaced with what you supply for the replaceWith parameter.
Here is an example of how it can be used:
String test = "This is a string which contains numFound=2,start=0,docs=[ crap and it may also "
+ "have numFound=1,start=0,docs=[ junk in it along with open curly bracket { and "
+ "the SolrDocument word which might also have ]}]} other crap in there too.";
testResult = customReplace(strg, "", "numFound=2,start=0,docs=[ ", "numFound=1,start=0,docs=[ ",
+ "{ ", "SolrDocument ", "]}]} ");
System.out.println(testResult);
You can also pass a single String Array which contains all your unwanted strings within its elements and pass that array to the stringsToReplace parameter, for example:
String test = "This is a string which contains numFound=2,start=0,docs=[ crap and it may also "
+ "have numFound=1,start=0,docs=[ junk in it along with open curly bracket { and "
+ "the SolrDocument word which might also have ]}]} other crap in there too.";
String[] unwantedStrings = {"numFound=2,start=0,docs=[ ", "numFound=1,start=0,docs=[ ",
"{ ", "SolrDocument ", "]}]} "};
String testResult = customReplace(test, "", unwantedStrings);
System.out.println(testResult);

Better string manipulation code

I'm looking for an efficient (one line) string manipulation code to achieve this, regex probably.
I have a string, for example, "Calvin" and I need to convert this to "/C/a/l/Calvin".
i.e. take first three characters, separate them using '/' and later append the original string.
This is the code I've come up with and its working fine, just looking for a better one.
String first = StringUtils.substring(prodName, 0, 1);
String second = StringUtils.substring(prodName, 1, 2);
String third = StringUtils.substring(prodName, 2, 3);
String prodPath = path + "/" + first + "/" + second + "/" + third + "/" + prodName + "/" ;
prodName.replaceAll("^(.)(.)(.).*", "/$1/$2/$3/$0")
What is the point of StringUtils.substring(prodName, 0, 1) when the built-in prodName.substring(0, 1) will do the same thing??
Anyway, assuming prodName is always at least 3 characters long (since you didn't give rules for expected output if it is not), this is the fastest way to do it:
String prodPath = path + '/' +
prodName.charAt(0) + '/' +
prodName.charAt(1) + '/' +
prodName.charAt(2) + '/' +
prodName + '/';
Normally, char + char is integer addition, not string concatenation, but since the first value is a String, and the + operator is left-associative, all + operators are string concatenations, not numeric additions.
How about using String.charAt
StringBuilder b = new StringBuilder (path);
b.append ('/').append (prodName.charAt (0))
.append ('/').append(prodName.charAt (1))
.append ('/').append(prodName.charAt (2))
.append ('/').append (prodName).append ('/');
Don't use regex for simple stuff like this. You may save a couple lines, but you loose a lot in readability. Regex usually take some time to understand when reading them.
String s = path;
for (int i = 0; i < 3; i++)
s += prodName.substring(i,i+1) + "/";
s += prodName
You can use MessageFormat.format()
MessageFormat.format("{0}/{1}/{2}/{3}/{4}/", baseDir, name.charAt(0), name.charAt(1), name.charAt(2), name);
imho i would wrap it for readability,
private String getProductionDirectoryPath(String baseDir, String name) {
return MessageFormat.format("{0}/{1}/{2}/{3}/{4}/", baseDir, name.charAt(0), name.charAt(1), name.charAt(2), name);
}
Positive look ahead can be used
public static void main(String[] args) {
String s = "Calvin";
System.out.println(s.replaceAll("(?=^(\\w)(\\w)(\\w))", "/$1/$2/$3/"));
}
O/P:
/C/a/l/Calvin
No use of a regex, but a simple split over nothing =)
String[] firstThree = prodName.split("");
String prodPath = path + "/" + firstThree[0] + "/" + firstThree[1] + "/" + firstThree[2] + "/" + prodName + "/";
Another approach is using charAt():
String prodPath = path + "/" + prodName.charAt(0) + "/" + prodName.charAt(1) + "/"+ prodName.charAt(2) + "/" + prodName + "/";
You said efficient but you maybe meant terse. I doubt either should be an objective, so you have a different problem.
Why do you care that this string transformation requires four lines of code? Are you concerned that something that in your mind is one operation ("create transformed string") is spread over four Java operations? You should extract the four lines of Java into their own method. Then, when you read the code where the operation is needed you have one conceptual operation ("create transformed string") corresponding to one Java operation (call a method). You could call the methid createTransformedString to make the code even clearer.
You can use String Builder:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++) {
sb.append("/").append(prodName.charAt(i));
}
sb.append('/').append(prodName);
Or you can put all the code in loop:
int size = 2;
StringBuilder sb = new StringBuilder();
for (int i = 0; i <= size; i++) {
if (i == 0)
sb.append('/');
sb.append(prodName.charAt(i)).append("/");
if (i == size)
sb.append(prodName);
}

replace substring defined by start and end index points?

I am working with this piece of code:
start = str.indexOf('<');
finish = str.indexOf('>');
between = str.substring(start + 1, finish);
replacement = str.substring(start, finish + 1);
System.out.println(between + " " + replacement); //for debug purposes
forreplacement = JOptionPane.showInputDialog(null, "Enter a " + between);
System.out.println(forreplacement); //for debug purposes
counter = counter - 1;
where "str" is the String that is being worked with. How do I replace the substring "replacement" with the string "forreplacement" (what is entered into the popup box) within the string str?
Not sure if that is what you want but maybe take part before start, add forreplacemeent and after that add part after finish like
String result = str.substring(0, start)+forreplacement+str.substring(finish+1);
Or if you want to replace all occurrences of replacement with forreplacement you can also use
String result = str.replace(replacement, forreplacement)
Your question is not clear. If you want to replace, you can do something like-
String str = "Hello World!";
String replacement = "World";
String stringToReplaceWith = "Earth";
str = str.replace(replacement, stringToReplaceWith);
System.out.println(str); // This prints Hello Earth!

Categories