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);
}
Related
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
I am using Spring MVC. I want to separate each declared string in another string by using comma and without using an array. And I need to pass that comma separated string in another Java file.
here is my code:
below is the model having three different setters and getters
public String pk1=getInstitutionId();
public String pk2=getInstitutionName();
public String pk3=getIsoCountryCode();
And Now I want to split this by using comma like this:
private String MultipleprimaryKeyStr= pk1 + "," + pk2 + "," + pk3;
But this pk1, pk2 and pk3 are taking as separate string. But MultipleprimaryKeyStr should take it as variable.
You have to do like
String MultipleprimaryKeyStr= params[0] + "," + params[1] + "," + params[2];
One more thing, I would like to tell you that you should not go in static but you should run while or for loop there like this:
String MultiplePrimaryKeyStr = "";
for(int i = 0; i < params.length; i++)
{
MultiplePrimaryKeyStr = ((i!=0) ? "," : "") + params[i];
}
By doing pk1 + "," + pk2 + "," + pk3 you are creating a new String because the operator + is used for concatenation operation in Strings.
So now you get this new String and you can split this String using split(",") as:
private String MultipleprimaryKeyStr= pk1 + "," + pk2 + "," + pk3;
String[] newStr= MultipleprimaryKeyStr.split(",");
By doing concatenation of multiple string into one string and those string is separated by comma.
Ex. String MultiplePrimaryKeyStr="This, is, separated, string";
just pass this string to new java file. And split in that file by calling split().
String[] sepratedString=MultiplePrimaryKeyStr.split(",");
process that string array inside loop.
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!
This question already has answers here:
String concatenation: concat() vs "+" operator
(12 answers)
Closed 9 years ago.
I am writing a file with possibly 1000 data points. I have classes for all of these and am currently writing all of the data at the end (the datapoints are taken at 1s intervals). What I am currently doing is written below, and it's very slow. Would I be better off changing how I am writing the string/bytes to the file? Or would I be better off writing this information to some file pointer as the application is running?
Btw, all of the things such as getAccuracy() and such are floats/ints (so it has to convert those also).
fileStr = "";
fileStr += "timestamp,Accuracy,Altitude,Latitude,Longitude,GPSSatelliteEntries\r\n";
for (Iterator<Entry> i = entries.iterator(); i.hasNext(); ) {
Entry item = i.next();
long ts = item.getTs();
DataEntry d = item.getD();
List<GPSSatelliteEntry> satellites = item.getG();
// write stuff
fileStr += ts + ",";
fileStr += d.getAccuracy() + "," + d.getAltitude() + "," + d.getLatittude() + "," + d.getLongitude() + ",";
fileStr += "[";
boolean entered = false;
for (Iterator<GPSSatelliteEntry> j = satellites.iterator(); j.hasNext(); ) {
GPSSatelliteEntry item2 = j.next();
entered = true;
fileStr += "(" + item2.getAzimuth() + "," + item2.getElevation() + "," + item2.getPrn() + "," + item2.getSnr() + "),";
}
// chop off extra ,
if (entered)
fileStr = fileStr.substring(0, fileStr.length() - 1);
fileStr += "]";
fileStr += "\r\n";
}
Everytime you have hard work with Strings, use StringBuilder or StringBuffer to achieve better performance .
Don't forget that String is immutable, and each time you modify String new instance will be created and it costs performance.
Most probably string buffer
A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified.
or go for string builder
StringBuilder stuff = new StringBuilder();
stuff.append("PUT YOUR STRINGS HERE");
stuff.append("PUT YOUR STRINGS HERE");
Then you can use 'stuff' to print the strings.
Put it in a loop and iterate over a large number with a timer to see the advantages, it's pretty interesting.
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;
}`