Concatenate is not being used - java

I have a simple method where the goal is to add "[" and "]" before and after every "."
For example:
Input: address = "1.1.1.1"
Output: "1[.]1[.]1[.]1"
Here is the function I've written, the problem here is where I have concatenate, why is this happening?
public static String defangIPaddr(String address) {
String returnStr = "";
for(int i = 0; i < address.length(); i++) {
char c = address.charAt(i);
if(c == '.') {
returnStr.concat("[");
returnStr.concat(".");
returnStr.concat("]");
} else {
returnStr.concat(address);
}
}
return returnStr;
}

Use replace() instead, just like this:
public static String defangIPaddr(String address) {
return address.replace(".", "[.]");
}

As has been explained, concat doesn't change the string, but rather returns a new string which is the concatenation of the two strings.
returnStr = returnStr.concat("[");
However, don't use concat. You rarely (if ever) need to use this. Instead use +=:
returnStr += "[";
But you don't even really want to use this, because it inefficiently creates a new string every time you do this. That's fine if the concatenation is a one-off, but you don't want to do this in a loop.
Use a StringBuilder instead, which allows you to append to the string without creating a new object each time:
String returnStr = new StringBuilder();
for(int i = 0; i < address.length(); i++) {
// ...
returnStr.append("[");
// ...
}
return returnStr.toString();
Or, of course, in this simple case, use replace.

Related

Java method to return String that can be used in SQL IN statement

I have a comma separated string that I need to convert in order to use it in an SQL IN statement e.g SELECT * FROM table WHERE filedvalue IN(conversion)
Below is the method I have come up with so far. The value being passed for Parameter parameter is GBL075,GBL008
public String paramconverter(String parameter)
{
String conversion="";
String newstring="";
String[] parts = parameter.split(",");
for(String part : parts)
{
newstring = newstring.concat("'"+part+"',");
}
conversion = new StringBuilder().append(newstring).toString();
int ind = conversion.lastIndexOf(",");
conversion = new StringBuilder(conversion).delete(ind,ind+1).toString();
System.out.println(conversion);
return conversion;
}
However when I read the console output I get the below results for Variable conversion
'GBL075','GBL008' 'GBL075','GBL008'
This obviously does not work in the sql statement. I need to correct this method and I need assistance. Thanks.
In Java 8 they added StringJoiner class:
StringJoiner joiner = new StringJoiner(", ");
joiner.add("foo");
joiner.add("bar");
joiner.add("baz");
String joined = joiner.toString(); // "foo, bar, baz"
Check this question, they offer different third party libs
A SQL variable contains a single value, not a list of values.
Some databases allow for lists to be passed (for example as a custom data type), but that is unusual and typically complex.
The usual solution is the build a SQL string without parameters. This feels wrong, but there is no better solution. For example:
sql = "select * from tbl where name in ("
for(int i = 0; i < array.length; i++)
{
if (i != 0)
sql += ", ";
sql += "'" + StringEscapeUtils.escapeSql(name) + "'";
}
sql += ");"
Note the use of escapeSql so the code works for names with a single quote.
public String paramconverter(String parameter){
StringTokenizer token = new StringTokenizer(parameter,",");
StringBuilder builder = new StringBuilder();
while(token.hasNext()){
builder.append("'");
builder.append(token.next());
builder.append("'");
if(builder.hasNext()){
builder.append(",");
}
}
return builder.toString();
}
OR
public String paramconverter(String parameter){
String res = ("'"+parameter+"'").replace(",","','");
return res;
}
Typical way of solving your problem (would be a beginner Java developer's solution):
String newstring="";
String[] parts = parameter.split(",");
for(String part : parts)
{
if (!newstring.isEmpty()) newstring += ",";
newstring += "'" + part + "'";
}
System.out.println(newstring);
return newstring;
There are more efficient ways of doing it. And, of course, you should escape single quotes, if you do not use prepared statements.
If you were asking me, I would do this at least (kind of itermediate level, but add parameter validation / NPE checks and you will see it in a lot of code):
//this class should be put for later re-use in the code
public class StringUtils {
public static String[] escapeAndQuote(String[] arr) {
String[] ret = new String[arr.length];
for (int i=0; i<arr.length; i++) {
ret[i] = "'" + arr[i].replace("'","''")+"'";
}
return ret;
}
public static String join(String delim, String[] arr) {
if (arr.length == 0) return "";
StringBuilder ret = new StringBuilder(arr[0]);
for (int i=1; i<arr.length; i++) {
ret.append(delim).append(arr[i]);
}
return ret.toString();
}
}
...
//this is how you use it
public String paramconverter(String parameter)
{
return StringUtils.join(",",StringUtils.escapeAndQuote(parameter.split(",")));
}
Even better way would be to do a monadic wrapper a-la jQuery, but it only pays off if you do a lot of stuff with Strings.
Last, but not least, if you know there are only 2 values, parametrized SQL query (prepared statement) is a way to go.

DeleteSubString in Java

I have written my own deleteSubString method as i'm experimenting creating all the java functions. However i'm having issues with the output it produces. Here is my code:
//deleteSubString
String subString = "ON";
String delString = "PONY";
String emp = "";
int delIndex = 0;
for(int i=0; i<delString.length()-1; i++){
if(delString.contains(subString)){
//do nothing
//read the rest of the string to confirm it contains
for(int j=delIndex; j<delString.length()-1; j++){
if(delString.contains(subString)){
//do nothing
}
else{
emp += delString.charAt(j);
}
}
}
System.out.println("Delete SubString");
System.out.println(emp);
}
What I expect to happen is the string to print out as "PY" but instead it chooses not to print anything at all. Any ideas would be greatly appreciated!
if(delString.contains(subString)){ is always true so emp is never set to a new String.
PONY contains ON and delString.length()-1 won't consider the last character,so your else part would not run.
Instead simply do
if(delString.contains(subString))
{
int delSize=subString.length();
int index1=delString.indexOf(subString);
int index2=index1+delSize;
return delString.substring(0,index1)+""+delString.substring(index2+1);
}
else return delString;
You have:
(delString.contains(subString))
This statement will always be true with the strings you've provided.
for(String s : delString.split(subString)) {
emp += s;
}
is this what you want?
String subString = "ONY";
String delString = "PONY";
String emp = "";
StringBuilder sb1=new StringBuilder(subString);
StringBuilder sb2=new StringBuilder(delString);
for(int i=0;i<sb2.length();i++)
{
for(int j=0;j<sb1.length();j++)
{
if(sb2.charAt(i)==sb1.charAt(j))
{
sb2.deleteCharAt(i);
}
}
}
emp=sb2.toString();
System.out.println(emp);
Sorry!!I have revamped the code but looks like its going to work fine...the problem with the string class is its immutability...The cod which you wrote doesnt give the require output...if it gives it can delete only first character i.e only O in your case Y is not getting deleted so i converted into StringBuffer class and wrote that..Happy Coding!

How to convert a string[] into string?

I know how to separate the string to string[]. In my project, I use t = time.split("-") to split a time into a string array t, and t[0]=DD, t[1]=MM. Now I need to convert the string array t into string time with format DD-MM. Did java have functions for that?
Guava does:
String joined = Joiner.on('-').join(parts);
On the other hand, I'd actually suggest not splitting and joining your string to start with. Instead, parse it into an appropriate date/time type (ideally Joda Time), perform any manipulation you need, and then reformat it using a different format pattern.
This will improve your error detection, and basically make your code really reflect the nature of the data you're working with - instead of just talking about splitting and joining text.
You can use String Utils from Apache Commons like this:
String res = StringUtils.join(myStrings, "-");
If you are not looking to use external frameworks, you can roll your own, like this:
StringBuilder res = new StringBuilder();
boolean isFirst = true;
for (String s : myStrings) {
if (!isFirst) {
res.append('-');
} else {
isFirst = false;
}
res.append(s);
}
public static String join(String[] arr, String separator)
{
StringBuilder b = new StringBuilder();
for(int i = 0; i < arr.length; i++)
{
if(i != 0) b.append(separator);
b.append(arr[i]);
}
return b.toString();
}
For this simple example, what's wrong with this?
String time = t[0]+"-"+t[1];
Yes, use StringBuilder when performance matters, but this is much more concise.

What is the most elegant way to convert a hyphen separated word (e.g. "do-some-stuff") to the lower camel-case variation (e.g. "doSomeStuff")?

What is the most elegant way to convert a hyphen separated word (e.g. "do-some-stuff") to the lower camel-case variation (e.g. "doSomeStuff") in Java?
Use CaseFormat from Guava:
import static com.google.common.base.CaseFormat.*;
String result = LOWER_HYPHEN.to(LOWER_CAMEL, "do-some-stuff");
With Java 8 there is finally a one-liner:
Arrays.stream(name.split("\\-"))
.map(s -> Character.toUpperCase(s.charAt(0)) + s.substring(1).toLowerCase())
.collect(Collectors.joining());
Though it takes splitting over 3 actual lines to be legible ツ
(Note: "\\-" is for kebab-case as per question, for snake_case simply change to "_")
The following method should handle the task quite efficient in O(n). We just iterate over the characters of the xml method name, skip any '-' and capitalize chars if needed.
public static String toJavaMethodName(String xmlmethodName) {
StringBuilder nameBuilder = new StringBuilder(xmlmethodName.length());
boolean capitalizeNextChar = false;
for (char c:xmlMethodName.toCharArray()) {
if (c == '-') {
capitalizeNextChar = true;
continue;
}
if (capitalizeNextChar) {
nameBuilder.append(Character.toUpperCase(c));
} else {
nameBuilder.append(c);
}
capitalizeNextChar = false;
}
return nameBuilder.toString();
}
Why not try this:
split on "-"
uppercase each word, skipping the first
join
EDIT: On second thoughts... While trying to implement this, I found out there is no simple way to join a list of strings in Java. Unless you use StringUtil from apache. So you will need to create a StringBuilder anyway and thus the algorithm is going to get a little ugly :(
CODE: Here is a sample of the above mentioned aproach. Could someone with a Java compiler (sorry, don't have one handy) test this? And benchmark it with other versions found here?
public static String toJavaMethodNameWithSplits(String xmlMethodName)
{
String[] words = xmlMethodName.split("-"); // split on "-"
StringBuilder nameBuilder = new StringBuilder(xmlMethodName.length());
nameBuilder.append(words[0]);
for (int i = 1; i < words.length; i++) // skip first
{
nameBuilder.append(words[i].substring(0, 1).toUpperCase());
nameBuilder.append(words[i].substring(1));
}
return nameBuilder.toString(); // join
}
If you don't like to depend on a library you can use a combination of a regex and String.format. Use a regex to extract the starting characters after the -. Use these as input for String.format. A bit tricky, but works without a (explizit) loop ;).
public class Test {
public static void main(String[] args) {
System.out.println(convert("do-some-stuff"));
}
private static String convert(String input) {
return String.format(input.replaceAll("\\-(.)", "%S"), input.replaceAll("[^-]*-(.)[^-]*", "$1-").split("-"));
}
}
Here is a slight variation of Andreas' answer that does more than the OP asked for:
public static String toJavaMethodName(final String nonJavaMethodName){
final StringBuilder nameBuilder = new StringBuilder();
boolean capitalizeNextChar = false;
boolean first = true;
for(int i = 0; i < nonJavaMethodName.length(); i++){
final char c = nonJavaMethodName.charAt(i);
if(!Character.isLetterOrDigit(c)){
if(!first){
capitalizeNextChar = true;
}
} else{
nameBuilder.append(capitalizeNextChar
? Character.toUpperCase(c)
: Character.toLowerCase(c));
capitalizeNextChar = false;
first = false;
}
}
return nameBuilder.toString();
}
It handles a few special cases:
fUnnY-cASe is converted to funnyCase
--dash-before-and--after- is converted to dashBeforeAndAfter
some.other$funky:chars? is converted to someOtherFunkyChars
For those who has com.fasterxml.jackson library in the project and don't want to add guava you can use the jaskson namingStrategy method:
new PropertyNamingStrategy.SnakeCaseStrategy.translate(String);
get The Apache commons jar for StringUtils. Then you can use the capitalize method
import org.apache.commons.lang.StringUtils;
public class MyClass{
public String myMethod(String str) {
StringBuffer buff = new StringBuffer();
String[] tokens = str.split("-");
for (String i : tokens) {
buff.append(StringUtils.capitalize(i));
}
return buff.toString();
}
}
As I'm not a big fan of adding a library just for one method, I implemented my own solution (from camel case to snake case):
public String toSnakeCase(String name) {
StringBuilder buffer = new StringBuilder();
for(int i = 0; i < name.length(); i++) {
if(Character.isUpperCase(name.charAt(i))) {
if(i > 0) {
buffer.append('_');
}
buffer.append(Character.toLowerCase(name.charAt(i)));
} else {
buffer.append(name.charAt(i));
}
}
return buffer.toString();
}
Needs to be adapted depending of the in / out cases.
In case you use Spring Framework, you can use provided StringUtils.
import org.springframework.util.StringUtils;
import java.util.Arrays;
import java.util.stream.Collectors;
public class NormalizeUtils {
private static final String DELIMITER = "_";
private NormalizeUtils() {
throw new IllegalStateException("Do not init.");
}
/**
* Take name like SOME_SNAKE_ALL and convert it to someSnakeAll
*/
public static String fromSnakeToCamel(final String name) {
if (StringUtils.isEmpty(name)) {
return "";
}
final String allCapitalized = Arrays.stream(name.split(DELIMITER))
.filter(c -> !StringUtils.isEmpty(c))
.map(StringUtils::capitalize)
.collect(Collectors.joining());
return StringUtils.uncapitalize(allCapitalized);
}
}
Iterate through the string. When you find a hypen, remove it, and capitalise the next letter.

Insert string in beginning of another string

How to insert a string enclosed with double quotes in the beginning of the StringBuilder and String?
Eg:
StringBuilder _sb = new StringBuilder("Sam");
I need to insert the string "Hello" to the beginning of "Sam" and O/p is "Hello Sam".
String _s = "Jam";
I need to insert the string "Hello" to the beginning of "Jam" and O/p is "Hello Jam".
How to achieve this?
The first case is done using the insert() method:
_sb.insert(0, "Hello ");
The latter case can be done using the overloaded + operator on Strings. This uses a StringBuilder behind the scenes:
String s2 = "Hello " + _s;
Other answers explain how to insert a string at the beginning of another String or StringBuilder (or StringBuffer).
However, strictly speaking, you cannot insert a string into the beginning of another one. Strings in Java are immutable1.
When you write:
String s = "Jam";
s = "Hello " + s;
you are actually causing a new String object to be created that is the concatenation of "Hello " and "Jam". You are not actually inserting characters into an existing String object at all.
1 - It is technically possible to use reflection to break abstraction on String objects and mutate them ... even though they are immutable by design. But it is a really bad idea to do this. Unless you know that a String object was created explicitly via new String(...) it could be shared, or it could share internal state with other String objects. Finally, the JVM spec clearly states that the behavior of code that uses reflection to change a final is undefined. Mutation of String objects is dangerous.
Sure, use StringBuilder.insert():
_sb.insert(0, _s);
You can add a string at the front of an already existing one. for example, if I have a name string name, I can add another string name2 by using:
name = name2 + name;
Don't know if this is helpful or not, but it works. No need to use a string builder.
private static void appendZeroAtStart() {
String strObj = "11";
int maxLegth = 5;
StringBuilder sb = new StringBuilder(strObj);
if (sb.length() <= maxLegth) {
while (sb.length() < maxLegth) {
sb.insert(0, '0');
}
} else {
System.out.println("error");
}
System.out.println("result: " + sb);
}
import java.lang.StringBuilder;
public class Program {
public static void main(String[] args) {
// Create a new StringBuilder.
StringBuilder builder = new StringBuilder();
// Loop and append values.
for (int i = 0; i < 5; i++) {
builder.append("abc ");
}
// Convert to string.
String result = builder.toString();
// Print result.
System.out.println(result);
}
}
It is better if you find quotation marks by using the indexof() method and then add a string behind that index.
string s="hai";
int s=s.indexof(""");

Categories