I have a small problem, but it's hard for me to solve it.
I have built a String that is a collection of some object's attributes, constructed and delimited by ||. But whenever I have some null attribute, it keeps on printing null, I want to replace null with empty string.
For example, for the input
ADS||abc||null||null
I want it to become
ADS||abc||||
I tried these two, but they didn't work:
string.replace(null,"")
string.replace("null","")
Can someone please help?
Since Strings are immutable, you should assign your String variable to the result of the replace method.
String str = "ADS||abc||null||null to become ADS||abc||||";
str = str.replace("null", "");
System.out.println(str);
Output:
ADS||abc|||| to become ADS||abc||||
Do you mean below code?
String[] names = new String("ADS||abc||null||null to become ADS||abc||||").split("\\|\\|");
List<String> list = new ArrayList<>();
for (String name : names) {
list.add(name.replace("null", ""));
}
This works fine.
public static void main(String[] args) {
String s = "ADS||abc||null||null";
s = s.replace("null", "");
System.out.println(s);
}
Output
ADS||abc||||
you forgot that string is immutable, add this to your code:
String string = string.replace("null","");
Related
I want to parse this string into a list and return {1.193493, 54.6333, 2.093077, 31.6235, 6.175355, 21.6479}. How do I get rid of the square brackets???? I used a for loop and replace but it doesn't work.
String st = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]"
String[] parsed = st.split(",");
for (String next : parsed) {
next.replace("//[", "").replace("//]", "");
}
replace() works with plain Strings, not regex. Therefore you can simply use:
next.replace("[", "").replace("]", "");
Also notice that you need to assign it to some string variable; assigning it to need won't work (won't modify elements in parsed array).
You should actually remove the braces first and split later, like this:
String[] parsed = st.replace("[", "").replace("]", "").split(",");
You can do it all at one time with this regex:
(?:\D*(\d*\.\d*))+
You can do this with one line:
List<String> list = Arrays.asList(t.replaceAll("\\[", "").replaceAll("\\]", "").split(","));
Full code:
package com.stackoverflow;
import java.util.Arrays;
import java.util.List;
public class Demo
{
public static void main(String[] args)
{
String t = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]";
List<String> list = Arrays.asList(t.replaceAll("\\[", "").replaceAll("\\]", "").split(","));
for(String s : list)
{
System.out.println(s);
}
}
}
Converts string to list of strings and prints it. If you need to convert strings to doubles, use Double.parseDouble(s) in loop.
You could achieve your goal in two steps.
1) Remove all special characters except comma (,)
2) Then split by comma (,)
public static void main(String[] args) {
String st = "[[[1.193493,54.6333],[2.093077,31.6235],[6.175355,21.6479]]]";
String[] parsed = st.replaceAll("[^\\d.,]+", "").split(",");
}
Output:
I need to concatenate a variable number of arguments (type String) to one String:
E.g.:
System.out.println( add("ja", "va") );
should return java but my implementation returns jaja.
I tried this:
public static String add(String... strings) {
for (String arg : strings) {
return String.format(arg.concat(arg));
}
return "string";
}
What am I doing wrong?
Nowadays you might want to use:
String.join(separator, strings)
You're returning on the first iteration of the loop (return String.format ...) rather than at the end. What you should use here is a StringBuilder:
public static String add(String... strings) {
StringBuilder builder = new StringBuilder();
for (String arg : strings) {
builder.append(arg);
}
return builder.toString(); //Outputs the entire contents of the StringBuilder.
}
Use Java 8's StringJoiner in combination with the stream API:
String joined = Stream.of(strings).collect(Collectors.joining());
Wrapped in a method, it could look like this:
import java.util.stream.Collectors;
import java.util.stream.Stream;
public static String join(String separator, String... strings) {
return Stream.of(strings).collect(Collectors.joining(separator));
}
There's plenty of ways, but a StringBuilder is probably the most efficient:
public static String add(String... strings) {
StringBuilder sb = new StringBuilder();
for (String arg : strings) {
sb.append(arg);
}
return sb.toString();
}
Basically, you initialise the builder as empty then loop through the arguments appending each one and finally return the contents of the builder.
You probably want to add some code in the loop to handle null values in the arguments (the array won't be null, but strings within it could be. As-is this method would append the string "null" for null values, which may not be what you want.
Try this:
String result;
for (int i =0, i < strings.size(), i++){
result += strings[i];
}
return result;
You could use the new Java 8 lambdas and something like,
String[] arr = { "ja", "va" };
Optional<String> result = Arrays.asList(arr).parallelStream()
.reduce(new BinaryOperator<String>() {
public String apply(String t, String u) {
return t + u;
}
});
System.out.println(result.get());
To answer your question, this line is what you are doing wrong:
return String.format(arg.concat(arg));
The first time in the for each loop arg would be the string ja. You take that string and concatenat with the same var arg which is ja. Then you return, so you never get into your second run of the loop.
To fix, do what others suggested and use something to collect and join for each variable.
To give you another solution to join, you can try to just join the varargs varible. So you can try:
return String.join ('',strings);
This way, no loop to write, just join the strings. This assumes Java 9.
I have the following piece of code
String Roletext=null;
for(String text1:Rolelist1)
{
Roletext+=text1+",";
}
I want to convert a list into a string. And then I display the value. It takes the null as it first value. If it is not initialized, then it will show error. Please help.
Solution for you question:
String Roletext="";
for(String text1:Rolelist1)
{
Roletext +=text1+",";
}
Reason for this is when you do concatenation with null , the string appends the value with "null"
My suggestion:
I suggest you to use StringBuilder instead of String concatenation.
StringBuilder b=new StringBuilder();
for(String text1:Rolelist1)
{
b.append(text1).append(",");
}
String Roletext=b.toString().replaceAll(",$", "");//get rid of last comma
You should initialize your String first
String Roletext="";
int i;
for(i = 0;i < Rolelist1.size() - 1;i++)
{
Roletext+=Rolelist1.get(i)+",";
}
Roletext+=Rolelist1.get(i);
Or for better performance you can use StringBuilder.
StringBuilder sb=new StringBuilder();
sb.append("Your String");
Define it like this:
String Roletext ="";
You have to inititalize the string first.
String Roletext="";
But it is not good practice to use a String object for building a string using a loop. Use StringBuilder instead:
StringBuilder sb = new StringBuilder();
for(String text1 : rolelist1) {
sb.append(text1);
}
roletext = sb.toString();
String Roletext="";
for(String text1:Rolelist1)
{
Roletext+=text1+",";
}
now it will not take any null values,initially the string is empty if String text="".
But if we are initializing it with null then String takes first value as null.
Null means some random value it doesn't means empty.
Do like this
String Roletext=null;
Rolelist1.remove(Collections.singleton(null)); //This line will remove all null from Rolelist1
for(String text1:Rolelist1)
{
Roletext+=text1+",";
}
String Roletext = Arrays.toString(Rolelist1.toArray());
This is a perfect example where using a StringBuilder is recommended:
StringBuilder roleText = new StringBuilder();
for(String text1:Rolelist1) {
if(roleText.length() > 0) {
roleText.append(",");
}
roleText.append(text1);
}
By the way: The if construct on length is the one I always use to prevent any leading or trailing commas, it's the most elegant solution to prevent this imo ;-)
I have a string which has the below content
String msg = "The variables &CHAG_EF and &CHAG_DNE_DTE can be embedded"
String test1 = "22/10/2010 00:10:12"
String test2 = "25/10/2010 00:01:12"
I need to search the string variable msg for the string "&CHAG_EF" and if it exists replace with the value of test1 and also search the string variable msg for the string "&CHAG_DNE_DTE" and if it exists replace with the value of test2.
How can i replace them?
So simple!
String msg2 = msg.replace("&CHAG_EF", test1).replace("&CHAG_DNE_DTE", test2);
Firstly, Strings can't be modified in Java so you'll need to create new versions with the correct modified values. There are two ways to approach this problem:
Dynamically hard-code all the replacements like other posters have suggested. This isn't scalable with large strings or a large number of replacements; or
You loop through the String looking for potential variables. If they're in your replacement Map then replace them. This is very similar to How to create dynamic Template String.
The code for (2) looks something like this:
public static String replaceAll(String text, Map<String, String> params) {
Pattern p = Pattern.compile("&(\\w+)");
Matcher m = p.matcher(text);
boolean result = m.find();
if (result) {
StringBuffer sb = new StringBuffer();
do {
String replacement = params.get(m.group(1));
if (replacement == null) {
replacement = m.group();
}
m.appendReplacement(sb, replacement);
result = m.find();
} while (result);
m.appendTail(sb);
return sb.toString();
}
return text;
}
Strings in Java are immutable, so any of the "manipulation" methods return a new string rather than modifying the existing one. One nice thing about this is that you can chain operations in many cases, like this:
String result = msg.replace("&CHAG_EF", test1)
.replace("&CHAG_DNE_DTE", test2);
msg = msg.replace("&CHAG_EF", test1).replace("&CHAG_DNE_DTE", test2);
The Java Docs for the method
String[] java.io.File.list(FilenameFilter filter)
includes this in the returns description:
The array will be empty if the directory is empty or if no names were accepted by the filter.
How do I do a similar thing and initialize a String array (or any other array for that matter) to have a length 0?
As others have said,
new String[0]
will indeed create an empty array. However, there's one nice thing about arrays - their size can't change, so you can always use the same empty array reference. So in your code, you can use:
private static final String[] EMPTY_ARRAY = new String[0];
and then just return EMPTY_ARRAY each time you need it - there's no need to create a new object each time.
String[] str = new String[0];?
String[] str = {};
But
return {};
won't work as the type information is missing.
Ok I actually found the answer but thought I would 'import' the question into SO anyway
String[] files = new String[0];
or
int[] files = new int[0];
You can use ArrayUtils.EMPTY_STRING_ARRAY from org.apache.commons.lang3
import org.apache.commons.lang3.ArrayUtils;
class Scratch {
public static void main(String[] args) {
String[] strings = ArrayUtils.EMPTY_STRING_ARRAY;
}
}
Make a function which will not return null instead return an empty array you can go through below code to understand.
public static String[] getJavaFileNameList(File inputDir) {
String[] files = inputDir.list(new FilenameFilter() {
#Override
public boolean accept(File current, String name) {
return new File(current, name).isFile() && (name.endsWith("java"));
}
});
return files == null ? new String[0] : files;
}
You can use following things-
1. String[] str = new String[0];
2. String[] str = ArrayUtils.EMPTY_STRING_ARRAY;<br>
Both are same.