Java Strip/Remove multiple words from a string - java

How to strip a string like this:
String a = "ItemStack{DIAMOND_HELMET x 1,UNSPECIFIC_META:{meta-type=UNSPECIFIC, display-name=PRO, repair-cost=1}}"
I want to get something like
"Diamond_HELMET 1 UNSPECIFIC PRO"
The methods I have tried is just replacing a bunch of strings, but its a pain in the *** and looks awful. Just wondering if anyone have a better solution/option.
Sorry forgot to add my own code :/
String itemStackStringName = "ItemStack{DIAMOND_HELMET x 1, UNSPECIFIC_META:{meta-type=UNSPECIFIC, display-name=PRO, repair-cost=1}}";
String getItemStacks = itemStackStringName.replace("ItemStack","")
.replace("{","").replace("}", "").replace("UNSPECIFIC_META:", "")
.replace("display-name", "").replace("=","")
.replace("meta-type", "").replace("repair-cost1", "")
.replace("x", "").replace(",","");
System.out.println(getItemStacks);
"DIAMOND_HELMET 1 UNSPECIFIC PRO"
It works, but its just a huge mess.

If you know that's the type your strings are going to be, you can go ahead and do something like this:
String arr[] = a.split("\\{");//you get an array of 3 strings
String someFinalString = arr[1].split("x")[0].trim();//you get "DIAMOND_HELMET"
someFinalString += arr[1].split("x")[1].split(",")[0];
arr = arr[2].split("\\=");//you get an array of 4 strings
someFinalString += " " + arr[1].split(",")[0] + " " + arr[2].split(",")[0];
In the future please post what you tried to do. Splitting something like this will always look awful. You can always make it concise later.
Just a proof this works (and you can figure out by yourself how to get lowercase I guess):

Related

How to increment a number in a String in Java?

I want to increment a number in a string in Java 8.
Like this:
String lifes = "3";
lifes--
But i know that way is impossible, does you know other way to do it?
Integer.parseInt("3") + 1
The above statement results 4 which means we are parsing the String value as Integer and then incrementing in here, hope it helps!
If the string only contains the number, I'd do something like this -
lifes = String.valueOf(Integer.parseInt(lifes) - 1);

Combining strings without using plus '+'

I am writing unit tests now and I need to create a specific string.
I have now defined something like this:
private final String at = "#:";
private String error, effect, one, two, three, four;
in setUp (#Before):
error = RandomStringUtils.randomAlphabetic (3);
one = RandomStringUtils.randomAlphabetic (6);
two = RandomStringUtils.randomAlphabetic (8);
three = RandomStringUtils.randomAlphabetic (2);
four = RandomStringUtils.randomAlphabetic (6);
effect = (error + at + one + at + two + at + three + at + four);
The combination of the strings with the pluses looks terribly ugly and amateurish. Is it possible to do it somehow more efficiently using anything else? For example pattern? I dont know. Thanks for help :)
For simplicity, you can also do:
String.join(at, error,one, two, three, four);
You can use the java built-in StringBuilder
StringBuilder sb = new StringBuilder();
sb.append(error);
sb.append(at);
sb.append(one);
...
effect = sb.toString();
If the "#:" is a consistent separator, and you're using Java 8+, you might find that String.join is your friend. This would look something like:
effect = String.join("#:", error, one, two, three, four);
Guessing a little bit from your variable names, but as a little background and just in case it's helpful, if you want/need to use a Stream you can also use Collectors.joining, which could look something like:
List<String> stringParts = ...
stringParts.stream()
.collect(Collectors.joining("#:"));
This will join everything in the list with "#:" as a delimiter. You can also add a constant prefix and/or suffix which might be relevant for your error variable, like:
String error = RandomStringUtils.randomAlphabetic(3);
List<String> stringParts = ...
stringParts.stream()
.collect(Collectors.joining("#:", error, ""));

Replace with empty space

I have done this before, but now I encounter a different problem. I want to extract just the digits at the end "Homework 1: 89", which is in a .txt file. As said I usually used ".replaceAll("[\D]", "")"* . But if I do it ths time, the number before the colon (1 in example) stays... I cannot see of any solution.
it Should look like this:
while (dataSc.hasNextLine()) {
String data = dataSc.nextLine();
ArrayData.add(i, data);
if (data.contains("Homework ")) {
idData.add(a, data);
idData.set(a, (idData.get(a).replaceAll("[\\D]", "")));
Output being, A new string with Just "89"...
Thanks for editing your question.
If you are simply trying to get the end whenever there is the word homework and you can count on the consistent format you can do the following:
String[] tokens = data.split(": ");
System.out.println(tokens[1]);
So if your looking in your code you would be wanting to place this in your if statement where you are trying to get only the numbers after the colon from data.
What the code does it breaks your string into multiple components, breaking it whenever it sees ": ".
In your example of "Homework 1: 89" it will break your data into two "tokens":
1:"Homework 1"
2:"89"
So when accessing the tokens array we access variable tokens[1] because the index starts at 0.
Use below code
1) String str="Homework 1: 89";
str = str.replaceAll("\\D+","");
2) String str="sdfvsdf68fsdfsf8999fsdf09";
String numberOnly= str.replaceAll("[^0-9]", "");
System.out.println(numberOnly);

How to delete duplicated characters in a string?

Okay, I'm a huge newbie in the world of java and I can't seem to get this program right. I am suppose to delete the duplicated characters in a 2 worded string and printing the non duplicated characters.
for example:I input the words "computer program." the output should be "cute" because these are the only char's that are not repeated.
I made it until here:
public static void main(String[] args) {
System.out.print("Input two words: ");
String str1 = Keyboard.readString();
String words[] = str1.split(" ");
String str2 = words[0] + " ";
String str3 = words[words.length - 1] ;
}
but i don't know how to output the characters. Could someone help me?
I don't know if I should use if, switch, for, do, or do-while...... I'm confused.
what you need is to build up logic for your problem. First break the problem statement and start finding solution for that. Here you go for steps,
Read every character from a string.
Add it to a collection, but before adding that, just check whether it exists.
If it exists just remove it and continue the reading of characteer.
Once you are done with reading the characters, just print the contents of collection to console using System.out.println.
I will recommend you to refer books like "Think like A Programmer". This will help you to get started with logic building.
Just a hint: use a hash map (http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html).
Adding following code after last line of your main program will resolve your issue.
char[] strChars = str2.toCharArray();
String newStr="";
for (char c : strChars) {
String charStr = ""+c;
if(!str3.contains(charStr.toLowerCase()) && !str3.contains(charStr.toUpperCase())){
newStr+=c;
}
}
System.out.println(newStr);
This code loops through all the characters of the first word and check if the second string contains that character (In any form of case Lower or Upper). If it is not containing, adding it to output string and at the end printing it.
Hope this will work in your case.
How about doing it in just 1 line?
str = str.replaceAll("(.)(?=.*\\1)", "");

Remove Punctuation issue

Im trying to find a word in a string. However, due to a period it fails to recognize one word. Im trying to remove punctuation, however it seems to have no effect. Am I missing something here? This is the line of code I am using: s.replaceAll("([a-z] +) [?:!.,;]*","$1");
String test = "This is a line about testing tests. Tests are used to examine stuff";
String key = "tests";
int counter = 0;
String[] testArray = test.toLowerCase().split(" ");
for(String s : testArray)
{
s.replaceAll("([a-z] +) [?:!.,;]*","$1");
System.out.println(s);
if(s.equals(key))
{
System.out.println(key + " FOUND");
counter++;
}
}
System.out.println(key + " has been found " + counter + " times.");
}
I managed to find a solution (though may not be ideal) through using s = s.replaceAll("\W",""); Thanks for everyones guidance on how to solve this problem.
You could also take advantage of the regex in the split operation. Try this:
String[] testArray = test.toLowerCase().split("\\W+");
This will split on apostrophe, so you may need to tweak it a bit with a specific list of characters.
Strings are immutable. You would need assign the result of replaceAll to the new String:
s = s.replaceAll("([a-z] +)*[?:!.,;]*", "$1");
^
Also your regex requires that a space exist between the word and the the punctuation. In the case of tests., this isn't true. You can adjust you regex with an optional (zero or more) character to account for this.
Your regex doesn't seem to work as you want.
If you want to find something which has period after that then this will work
([a-z]*) [?(:!.,;)*]
it returns "tests." when it's run on your given string.
Also
[?(:!.,;)*]
just points out the punctuation which will then can be replaced.
However I am not sure why you are not using substring() function.

Categories

Resources