Replace generic character in a Java string - java

I'm wondering about how to replace generic characters in a Java string:
String original = "alt width = (SOME NUMBERS)"
and I want to make it like
String edited = "alt width = 640"
I haven't found out anything about on the web.

To be generic enough to replace any integer number:
int number; // this can be any integer
String original = String.format("alt width = %d",number);
Or if the numbers are represented as a String e.g "111,121"
String numbers;
String original = String.format("alt width = %s",numbers);

The replace method should do the trick:
String edited = original.replace("(SOME NUMBERS)", "640");
EDIT:
Based on the clarification in the comments, you could just remove the last three characters and replace them with what you need:
String edited = original.substring(0, original.length() - 3) + "640";

The most obvious answer is String.replace option. but you already got that answer.
A more generic option is using regular expressions:
String original = "alt width = 123";
int someNumbers = 640;
String edited=original.replaceFirst("[0-9]+",Integer.toString(someNumbers));
System.out.println(edited);
This will replace any numbers on the string. So the input string can be different but you'll get the same results:
String original = "alt width = 123 cm";
String original = "alt width = 123; alt height = 456"; //only 123 will be replaced 456 will be left as is.
You can modify the regex to fit other criteria.

Related

Java find not so specific String

I have product description, furniture, many words and I need to find the size (dimensions) of the product. The problem is, the format of the description of the size is not always the same. Only one thing stays same : letter "x" between the numbers, and if there is "x" in the text and another "x" just a few chars away, it is for sure the size description.
Possible formats of size description /all of them appears/:
size:110x76x60 cm /without spaces/
size: 150 x 64,5 x 200 cm /with spaces/
Size: l90 x h55 x w60 cm /as length, height, width/
Size: 149 x v110 x h40 /only some numbers have letters before them/
And not to mention, the numbers dont have to be 3 digits, they can be only 2 digits. But if it is easier to do it for only one type of format, I take it :) and I let the program check the whole list for all the possible formats again and again.
What have you tried so far?
Sounds like a perfect job for a regular expression
JavaDocs have a wealth of information on regular expressions and how to implement them in java code here:
https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
I'm not proud of it, but it works and should give you an idea for making it recursive. It will also allow you to NOT learn regex, which not everyone wants to learn:
This code works and will get you the sizes you are looking for:
public class App {
public static void main(String[] args) {
int l;
int h;
int w;
String text = "Size: l90 x h55 x w60";
String text2 = text.replaceAll("\\D+"," ").trim();
System.out.println(text2);
String[] sizes = text2.split(" ");
l = Integer.valueOf(sizes[0]);
h = Integer.valueOf(sizes[1]);
w = Integer.valueOf(sizes[2]);
}
}
You can use a Matcher and a regular expression.
Matcher matcher = Pattern.compile("(\d+(?:,\d+)?) *x *[a-zA-Z]*(\d+(?:,\d+)?) *x *[a-zA-Z]*(\d+(?:,\d+)?)").matcher(productDescription);
while (matcher.find()) {
String number1 = matcher.group(1);
String number2 = matcher.group(2);
String number3 = matcher.group(3);
}

String.format() for string and numbers in Java

I will prepare String for use substring function and i need to have always 4 characters. In stackoverflow I found code like this but it is works only for numbers.
writeHead = String.format("%04d", writeHead);
But in my case i need to do this same for text + numbers.
12a --> 012a
String head = "12a";
String writeHead = String.format("%04d", head);//doesnt work
//need 012a as String
String.format is not good if yor text/number pattern is fixed (i.e. all your numbers ends with letter a?).
A quick and dirty left padding with zeroes:
String head="12a";
String writeHead = "0000"+head;
writeHead=writeHead.substring(writeHead.length()-4);
a simple thing like this will do
String head = "12a";
while(head.length < 4){
head += "0"+head;
}
just check the length and append
int head = 12;
String writeheader = String.format("0%da", head);
or
String header = 12a;
String writeHeader = String.format("0%s", head);

Splitting a string from url pattern

I have a string in the format: /constant/variableurl . What is the best way out, such that, I can get the variableurl alone as a string.
I understand string tokenizer and regex are the two way out, but not sure how to split the last variableurl alone.
Any help is appreciated.
According to your explanation and example this is code that you could use (not perfect, generic)
toFind.substring(toFind.lastIndexOf("/") + 1)
where
String toFind = "/constant/variableurl"
There are many ways to achieve that:
String[] res = myStr.split("\\/");
String myStr = res[res.length - 1];
myStr = myStr.substring(myStr.lastIndexOf('/') + 1);
...
To add more methods, visit the docs.
If the constant portion of the string is the same for all your strings, you can get the variable portion of it using substring, and passing the length of the common part:
String a = "/constant/hello/world";
String b = "/constant/quick/brown/fox";
String c = "/constant/jumps/over/the/lazy/dog";
int len = "/constant/".length(); // That's 10
a = a.substring(len); // Becomes "hello/world"
b = a.substring(len); // Becomes "quick/brown/fox"
c = a.substring(len); // Becomes "jumps/over/the/lazy/dog"

How can I create a string from the parent string from some int position in parent string?

Ok let me give an example:
String parentString = "HelloThisIsAString";
int stringPos = parentString.indexOf("String"); //Will return the position of the text "String" of the parentString.
String string = //Here the problem arises.
In python I do it like this:
string = parentString[stringPos:#to some certain text]
How to do it in Java.
You can use substring method, like this:
String parentString = "HelloThisIsAString";
int stringPos = parentString.indexOf("String");
String string = parentString.substring(stringPos, toSomePos);
// ^^^
// |
// This is optional
Dropping the last parameter gives you a substring from the specific position to the end of the original string.

Short string format

I've an array with hundreds of string values, Is it possible to use specific formats to make them shorter?
e.g
Normal -> "Hello John, What's up?!"
With short format -> "Hello John..."
After using substring, I got errors.
private String[] finalString;
for (int i = 0; i < arrays.PodcastTitle.length; i++) {
finalString[i] = arrays.PodcastTitle[i].substring(0, 5);
}
Since you haven't given any details, this is the shortest approach :
String little = normalString.substring(0, 10); // use anything 5 or 10 or 15, depending on how short you want to make your String
From your edit:
Please change:
private String[] finalString;
to:
private String[] finalString = new String[whateverSizeYouWant];
String toLitteString(String str, int length) {
if (str.length() > length) return str.substring(0, length) + "...";
return str;
}
Function that will truncate longer strings to length (and add a "...") or return the short string. If you want the length to include the "..." then just change length to length - 3.
Why won't you consider implementing a method that takes a String argument, explodes it by space character and returns the String with required number of words in it?

Categories