Is there a difference between concatenating strings with '' and ""?
For example, what is the difference between:
String s = "hello" + "/" + "world";
and
String s = "hello" + '/' + "world";
Literals enclosed in double quotes, e.g. "foo", are strings, whereas single-quoted literals, e.g. 'c', are chars. In terms of concatenation behaviour, there'll be no discernible difference.
Nevertheless, it's worth remembering that strings and chars aren't interchangeable in all scenarios, and you can't have a single-quoted string made up of multiple characters.
System.out.println('a'+'b'+'c');
> 294
System.out.println("a"+"b"+"c");
> abc
What's happening here is that (char)+(char)=(int)
In other words. Use "" for text to avoid surprises.
"." is a String, '.' is a char.
You may just look into the JDK :-)
Given two functions:
public static String concatString(String cs) {
return "hello" + cs + "world";
}
public static String concatChar(char cc) {
return "hello" + cc + "world";
}
after examination of the bytecode it boils down to two AbstractStringBuilder.append(String) vs. AbstractStringBuilder.append(char).
Both methods invoke AbstractStringBuilder.expandCapacity(int)) which will allocate a new char[] eventually and System.arraycopy the old content first.
Afterwards AbstractStringBuilder.append(char) just has to put the given char in the array whereas AbstractStringBuilder.append(String) has to check a few constraints and calls String.getChars(int, int, char[], int) which does another System.arraycopy of the appended string.
"." is a String consisting of only one character. '.' is a character.
Once you concatenate them together there is no difference.
'' is for character literals.
So you cannot do this:
"Osc" + 'ar' + "Reyes"
Because ar is not a character literal.
In your example it doesn't make much difference because
'/'
is a char literal, and
"/"
is a String literal containing only one character.
Additionally you can use any UTF character with the following syntax
'\u3c00'
So you can also use:
"Osc" + '\u3c00' + "ar
Adding a char is about 25% faster than adding a one character String. Often this doesn't matter however, for example
String s = "hello" + "/" + "world";
This is converted to one String by the compiler so no String concatenation/append will occur at run-time in any case.
Theoretically it is quicker to add a char to a string - Java 6 seems to create StringBuffers under the covers and I remember reading on a Java Performance site that concatenating a char will be marginally quicker.
You will probably find the following articles useful:
Java String Performance Testing
Java String Concatenation
char theLetterA = 'A';
string myString = "a string";
you can only put a single char in between '' if you want to add some more characters use those in between "".
as string is a collection of characters like strong text"hello world"
we can have same thing by using '' like- 'h' 'e' 'l' 'l' 'o' .....
and each has to be stored in different char variable which can be very hectic
so use "" when you have more than one char to store and '' for single char
Related
Isn't it possible to Change a specific digit/letter or even a space in a string and set it to another one?
Example:
String test = "name1 name2 name3 name4"
and I want to convert it into another String so that it could look like this:
String test2 = "name1+name2+name3+name4"
So how can I tell it to set all "spaces" to a +?
Use replaceAll()
test2=test.replaceAll("\\s","+");
Try String.replaceAll()
test2 = test.replaceAll("\\s","+");
Note :
(Regex) \s : (Description) A whitespace character, short for [ \t\n\x0b\r\f]
and since this is a special character it is preceeded by one more \
Use String#replaceAll("\\s", "+") method
You should look into repalceAll() in String class
test2=test1.replaceAll(" ","+");
What you'll need to do is search the string for the spaces and each time you've found one replace it with a designated character.
In Java there are functions to do this for you. Such as ReplaceAll(oldStr, newStr), where oldStr can accept a regular expression and newStr is the replacement.
String test = "name1 name2 name3 name4";
test = test.ReplaceAll(" ","+");
System.out.println(test);
The output is:
name1+name2+name3+name4
Instead of typing a space: " "
You may add the exact character code (ASCII code) you wish to replace by using:
Character.toString ((char) i)
Where i is the ASCII number.
So the equivalent would be:
test = test.ReplaceAll(Character.toString ((char) 32), Character.toString ((char) 43));
Hope this helps :)
String realstring = "&&&.&&&&";
Double value = 555.55555;
String[] arraystring = realstring.split(".");
String stringvalue = String.valueof(value);
String [] valuearrayed = stringvalue.split(".");
System.out.println(arraystring[0]);
Sorry if it looks bad. Rewrote on my phone. I keep getting ArrayIndexOutOfBoundsException: 0 at the System.out.println. I have looked and can't figure it out. Thanks for the help.
split() takes a regexp as argument, not a literal string. You have to escape the dot:
string.split("\\.");
or
string.split(Pattern.quote("."));
Or you could also simply use indexOf('.') and substring() to get the two parts of your string.
And if the goal is to get the integer part of a double, you could also simply use
long truncated = (long) doubleValue;
split uses regex as parameter and in regex . means "any character except line separators", so you could expect that "a.bc".split(".") would create array of empty strings like ["","","","",""]. Only reason it is not happening is because (from split javadoc)
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
so because all strings are empty you get empty array (and that is because you see ArrayIndexOutOfBoundsException).
To turn off removal mechanism you would have to use split(regex, limit) version with negative limit.
To split on . literal you need to escape it with \. (which in Java needs to be written as "\\." because \ is also Strings metacharacter) or [.] or other regex mechanism.
Dot (.) is a special character so you need to escape it.
String realstring = "&&&.&&&&";
String[] partsOfString = realstring.split("\\.");
String part1 = partsOfString[0];
String part2 = partsOfString[1];
System.out.println(part1);
this will print expected result of
&&&
Its also handy to test if given string contains this character. You can do this by doing :
if (string.contains(".")) {
// Split it.
} else {
throw new IllegalArgumentException("String " + string + " does not contain .");
}
I want to remove that characters from a String:
+ - ! ( ) { } [ ] ^ ~ : \
also I want to remove them:
/*
*/
&&
||
I mean that I will not remove & or | I will remove them if the second character follows the first one (/* */ && ||)
How can I do that efficiently and fast at Java?
Example:
a:b+c1|x||c*(?)
will be:
abc1|xc*?
This can be done via a long, but actually very simple regex.
String aString = "a:b+c1|x||c*(?)";
String sanitizedString = aString.replaceAll("[+\\-!(){}\\[\\]^~:\\\\]|/\\*|\\*/|&&|\\|\\|", "");
System.out.println(sanitizedString);
I think that the java.lang.String.replaceAll(String regex, String replacement) is all you need:
http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll(java.lang.String, java.lang.String).
there is two way to do that :
1)
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("+");
arrayList.add("-");
arrayList.add("||");
arrayList.add("&&");
arrayList.add("(");
arrayList.add(")");
arrayList.add("{");
arrayList.add("}");
arrayList.add("[");
arrayList.add("]");
arrayList.add("~");
arrayList.add("^");
arrayList.add(":");
arrayList.add("/");
arrayList.add("/*");
arrayList.add("*/");
String string = "a:b+c1|x||c*(?)";
for (int i = 0; i < arrayList.size(); i++) {
if (string.contains(arrayList.get(i)));
string=string.replace(arrayList.get(i), "");
}
System.out.println(string);
2)
String string = "a:b+c1|x||c*(?)";
string = string.replaceAll("[+\\-!(){}\\[\\]^~:\\\\]|/\\*|\\*/|&&|\\|\\|", "");
System.out.println(string);
Thomas wrote on How to remove special characters from a string?:
That depends on what you define as special characters, but try
replaceAll(...):
String result = yourString.replaceAll("[-+.^:,]","");
Note that the ^ character must not be the first one in the list, since
you'd then either have to escape it or it would mean "any but these
characters".
Another note: the - character needs to be the first or last one on the
list, otherwise you'd have to escape it or it would define a range (
e.g. :-, would mean "all characters in the range : to ,).
So, in order to keep consistency and not depend on character
positioning, you might want to escape all those characters that have a
special meaning in regular expressions (the following list is not
complete, so be aware of other characters like (, {, $ etc.):
String result = yourString.replaceAll("[\\-\\+\\.\\^:,]","");
If you want to get rid of all punctuation and symbols, try this regex:
\p{P}\p{S} (keep in mind that in Java strings you'd have to escape
back slashes: "\p{P}\p{S}").
A third way could be something like this, if you can exactly define
what should be left in your string:
String result = yourString.replaceAll("[^\\w\\s]","");
Here's less restrictive alternative to the "define allowed characters"
approach, as suggested by Ray:
String result = yourString.replaceAll("[^\\p{L}\\p{Z}]","");
The regex matches everything that is not a letter in any language and
not a separator (whitespace, linebreak etc.). Note that you can't use
[\P{L}\P{Z}] (upper case P means not having that property), since that
would mean "everything that is not a letter or not whitespace", which
almost matches everything, since letters are not whitespace and vice
versa.
For example: after execution, the output of the String "hello world yo" and "hello world yo" should be strictly the same.
what's more, the output should be a String[] in which:
String[0] == "hello"; String[1] == "world"; String[2] == "yo";
so that other method can deal with the effective words latter.
I was thinking about String.split(" "), but the blanks between the words are uncertain, and will then cause an exception..
You can use
String.split("\\s+") // one or more whitespace.
Dont use == for string comaprision instead use String.equals()
Edit for question in comment
what's the notation called? what if there is one or more "_" or "\n" ?
As you can see String#split() API accepts regex as parameter. The \s is shorthand character class for whitespace, whereas + is used to repeats the previous item once or more.
Now if you want to split String on
_ ie. underscore --> "this__is_test".split("[_]+");
\n ie. newline --> "this__is_test\n new line".split("\\r?\\n");
Regex Tutorial
You can split on "\\s+". That splits on one or more whitespace characters.
String.split() takes a regexp, so you can simply do String.split(" +").
I think the split function takes regex, but if it doesn't then the below works.
The regex in this might not be right, but it demonstrates the concept of what you're trying to do.
Pattern p = Pattern.compile("(.*?) *(.*)");
Matcher m = p.matcher(s);
if (m.matches()) {
String name = m.group(1);
String value = m.groupo(2);
}
for (int i = 1; i<=m.groupCount(); i++) {
System.out.println(m.group(i));
}
you can use Regular Expression to split the String.
String.split(Regular Expression);
for multiple whitespace, you can use Regular Expression: " \\s+ ", which 's' stand for space.
"==" operator used to judge whether left and right is equal. for String, they are Object actually, which means that they are regard as reference(like the pointer in C).
So if you want compare the content of two Strings, you can use method equals(String) of String.
e.g. str1.equals(str2)
What's the difference between java.lang.String 's replace() and replaceAll() methods,
other than later uses regex? For simple substitutions like, replace . with / ,
is there any difference?
In java.lang.String, the replace method either takes a pair of char's or a pair of CharSequence's (of which String is a subclass, so it'll happily take a pair of String's). The replace method will replace all occurrences of a char or CharSequence. On the other hand, the first String arguments of replaceFirst and replaceAll are regular expressions (regex). Using the wrong function can lead to subtle bugs.
Q: What's the difference between the java.lang.String methods replace() and replaceAll(), other than that the latter uses regex.
A: Just the regex. They both replace all :)
http://docs.oracle.com/javase/8/docs/api/java/lang/String.html
PS:
There's also a replaceFirst() (which takes a regex)
Both replace() and replaceAll() replace all occurrences in the String.
Examples
I always find examples helpful to understand the differences.
replace()
Use replace() if you just want to replace some char with another char or some String with another String (actually CharSequence).
Example 1
Replace all occurrences of the character x with o.
String myString = "__x___x___x_x____xx_";
char oldChar = 'x';
char newChar = 'o';
String newString = myString.replace(oldChar, newChar);
// __o___o___o_o____oo_
Example 2
Replace all occurrences of the string fish with sheep.
String myString = "one fish, two fish, three fish";
String target = "fish";
String replacement = "sheep";
String newString = myString.replace(target, replacement);
// one sheep, two sheep, three sheep
replaceAll()
Use replaceAll() if you want to use a regular expression pattern.
Example 3
Replace any number with an x.
String myString = "__1_6____3__6_345____0";
String regex = "\\d";
String replacement = "x";
String newString = myString.replaceAll(regex, replacement);
// __x_x____x__x_xxx____x
Example 4
Remove all whitespace.
String myString = " Horse Cow\n\n \r Camel \t\t Sheep \n Goat ";
String regex = "\\s";
String replacement = "";
String newString = myString.replaceAll(regex, replacement);
// HorseCowCamelSheepGoat
See also
Documentation
replace(char oldChar, char newChar)
replace(CharSequence target, CharSequence replacement)
replaceAll(String regex, String replacement)
replaceFirst(String regex, String replacement)
Regular Expressions
Tutorial
List of patterns
The replace() method is overloaded to accept both a primitive char and a CharSequence as arguments.
Now as far as the performance is concerned, the replace() method is a bit faster than replaceAll() because the latter first compiles the regex pattern and then matches before finally replacing whereas the former simply matches for the provided argument and replaces.
Since we know the regex pattern matching is a bit more complex and consequently slower, then preferring replace() over replaceAll() is suggested whenever possible.
For example, for simple substitutions like you mentioned, it is better to use:
replace('.', '\\');
instead of:
replaceAll("\\.", "\\\\");
Note: the above conversion method arguments are system-dependent.
Both replace() and replaceAll() accepts two arguments and replaces all occurrences of the first substring(first argument) in a string with the second substring (second argument).
replace() accepts a pair of char or charsequence and replaceAll() accepts a pair of regex.
It is not true that replace() works faster than replaceAll() since both uses the same code in its implementation
Pattern.compile(regex).matcher(this).replaceAll(replacement);
Now the question is when to use replace and when to use replaceAll().
When you want to replace a substring with another substring regardless of its place of occurrence in the string use replace(). But if you have some particular preference or condition like replace only those substrings at the beginning or end of a string use replaceAll(). Here are some examples to prove my point:
String str = new String("==qwerty==").replaceAll("^==", "?"); \\str: "?qwerty=="
String str = new String("==qwerty==").replaceAll("==$", "?"); \\str: "==qwerty?"
String str = new String("===qwerty==").replaceAll("(=)+", "?"); \\str: "?qwerty?"
To throw more light with an example into how both are going to work for below code:
public static void main(String[] args)
{
String s = "My\\s aaab\\s is\\s aaab\\s name";
String s1 = s.replace("\\s", "c");
System.out.println(s1);
String s2 = s.replaceAll("\\s", "c");
System.out.println(s2);
}
Output:
Myc aaabc isc aaabc name
My\scaaab\scis\scaaab\scname
Explanation
s.replace replaces "\\s" sequence of characters with c. Hence, the output in first line.
s.replaceAll considers \\s as a regex rather(equivalent to space) and replaces spaces with c. \\s in String s is escaped with first \ encountered and becomes \s.
Intellij Idea is smart enough to notify you of the usage as well. If you take a closer look at below image, you will see the difference in interpretation by Intellij idea for replace and replaceAll usage.
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the given replacement.
Old thread I know but I am sort of new to Java and discover one of it's strange things. I have used String.replaceAll() but get unpredictable results.
Something like this mess up the string:
sUrl = sUrl.replaceAll( "./", "//").replaceAll( "//", "/");
So I designed this function to get around the weird problem:
//String.replaceAll does not work OK, that's why this function is here
public String strReplace( String s1, String s2, String s )
{
if((( s == null ) || (s.length() == 0 )) || (( s1 == null ) || (s1.length() == 0 )))
{ return s; }
while( (s != null) && (s.indexOf( s1 ) >= 0) )
{ s = s.replace( s1, s2 ); }
return s;
}
Which make you able to do:
sUrl=this.strReplace("./", "//", sUrl );
sUrl=this.strReplace( "//", "/", sUrl );
As alluded to in wickeD's answer, with replaceAll the replacement string is handled differently between replace and replaceAll. I expected a[3] and a[4] to have the same value, but they are different.
public static void main(String[] args) {
String[] a = new String[5];
a[0] = "\\";
a[1] = "X";
a[2] = a[0] + a[1];
a[3] = a[1].replaceAll("X", a[0] + "X");
a[4] = a[1].replace("X", a[0] + "X");
for (String s : a) {
System.out.println(s + "\t" + s.length());
}
}
The output of this is:
\ 1
X 1
\X 2
X 1
\X 2
This is different from perl where the replacement does not require the extra level of escaping:
#!/bin/perl
$esc = "\\";
$s = "X";
$s =~ s/X/${esc}X/;
print "$s " . length($s) . "\n";
which prints
\X 2
This can be quite a nuisance, as when trying to use the value returned by java.sql.DatabaseMetaData.getSearchStringEscape() with replaceAll().
From Java 9 there is some optimizations in replace method.
In Java 8 it uses a regex.
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
From Java 9 and on.
And Stringlatin implementation.
Which perform way better.
https://medium.com/madhash/composite-pattern-in-a-nutshell-ad1bf78479cc?source=post_internal_links---------2------------------
replace() method doesn't uses regex pattern whereas replaceAll() method uses regex pattern. So replace() performs faster than replaceAll().
To add to the already selected "Best Answer" (and others that are just as good like Suragch's), String.replace() is constrained by replacing characters that are sequential (thus taking CharSequence). However, String.replaceAll() is not constrained by replacing sequential characters only. You could replace non-sequential characters as well as long as your regular expression is constructed in such a way.
Also (most importantly and painfully obvious), replace() can only replace literal values; whereas replaceAll can replace 'like' sequences (not necessarily identical).
replace works on char data type but replaceAll works on String datatype and both replace the all occurrences of first argument with second argument.