Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
String s = "world";
StringBuilder str = new StringBuilder(s);
str.deleteCharAt(0);
System.out.println(s);
this code outputs the following result : world , what am i doing wrong ? why is the first character of string not being deleted ?
The Issue with the StringBuilder and your code is that it does not exactly what you think it does.
A StringBuilder may take any CharSequence as a constructor argument but it will not alter the passed value directly. String in particular are immutable. Anyway StringBuilders do not alter the Object directly. They buffer the characters in a char[] which isn't immutable anymore.
To get the buffered value (and your new "altered" String) you have to call the toString() method of the StringBuilder since it will create a new String based on the interally stored buffer.
But since it System.out.println() implicitly calls the toString() method it is not needed here.
System.out.println(str);
you must put the value of your StringBuilder back to your string.
s = str.toString();
You are printing s, and s has not been changed. When you construct str using s, a copy of s is made. Told in a different way, the reference to each character in s and str is not the same, so even after your deletion in str, s stays the same.
Modify
System.out.println(s);
to
System.out.println(str.toString());
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
There are way too many ways to concatenate strings and add variable values in Java. How should I select one (pros, cons, best use cases, etc).
MessageFormat.format
String.format
"string a" + "string b"
StringBuilder
StringBuffer
String.concat
Streams
String.join()
Apache Commons’ StringUtils
Google Guava’s Joiner
...
MessageFormat.format() - Used for dynamically created strings, where parts of the string are positioned and the arguments fill up the place.
MessageFormat.format("My name is {0}. I am {1} years old", "Vignesh", 24);
String.format() - Like position numbering in MessageFormat, it accepts the argument type specifiers.
String.format("Pi is %.2f", 3.14)
String+String - string+string produces a new string leaving the older ones in the garbage, which gets cleared later by JVM.
It internally gets converted to StringBuilder.append() and toString() methods.
hello+world=helloworld null+hello=nullhello
String.concat() - Unlike string+string, if the object on which concat method is called is null, NullPointerException will be thrown.
String a = null, b="hello"; a.concat(b) throws NullPointerException
StringBuffer - They are mutable but they are slower as the methods inside them are synchronized. ie., thread safe
StringBuffer sb = new StringBuffer();
sb.append("hello").append("world");
sb.toString();
StringBuilder - They are mutable and faster than StringBuffer, but not thread safe
StringBuilder sb = new StringBuilder();
sb.append("hello").append("world");
sb.toString();
String.join - If the strings to be concatenated is in the form of array, its better to use String.join rather than looping through the array and appending using a StringBuilder, which String.join does it already inernally. If the array passed is null, it throws NullPointerException.
String[] a = {"hello", "world"};
String.join("", a)
StringUtils.join - If the strings to be concatenated is in the form of array, this can also be used. It internally uses StringBuilder. But just for string concatenation there is no need to include a jar. It precalcualtes the capacity of the StringBuilder object based on the numnber of elements in the array. If the array passed is null, it doesn't throws exception but just returns null string.
String[] a = {"hello", "world"};
StringUtils.join(a, "")
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I get this error "cannot resolve symbol method ‘split’ (java lang string)", when I try using the code below.
What could be causing the "split" error?
What is required to use "split" do I need to import android?
public void run() {
byte[] buffer = new byte[2048];
int mybytes;
String fields[];
while (true) {
try {
mybytes = mmInStream.read(buffer);
String readMessage = new String(buffer, 0, mybytes);
System.out.print("|mybytes|:\t" + mybytes);
fields = mybytes.split(" ");
heat = Integer.parseInt(fields[1]);
speed = Integer.parseInt(fields[3]);
You need to Declare Your mybytes as String not as a int change it
Use this
String mybytes;
Instead of this
int mybytes;
Okay, first off I'll address your question:
You're trying to perform a split on an int, not a stream, change the line
fields = mybytes.split(" ");
to
fields = readMessage.split(" ");
Regarding the structure of the questions itself:
Next time you're going to ask a question refer to How to ask.
Please provide the log-cat (or just stack-trace) for the error.
Please explain what you tried to do.
Please provide the entire code related to your problem, and not just a couple of lines with a bunch of blank lines inside of them.
Again, next time please refer to the How to ask because if you post a question in the same format, you might very well be blocked from asking questions again.
I think you intend to split buffer, not mbytes
You are trying to split an int. Instead, use a String, like :
String mybytes;
mybytes = String.valueOf(mmInStream.read(buffer));
fields = mybytes.split(" ");
Or you can use
fields = readMessage.split(" ");
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
public class StringDemo
{
public static void main(String [] args)
{
String s = "Sachin";
s.concat(" Tendulkar");
s.toLowerCase();
System.out.print(s);
}
}
This example giving output as : Sachin
then how many objects have been created?
The answer is: an indeterminate number.
on the face of it, the two operations on s each create a single String object,
two more String objects are created at load time to represent the literals,
objects may be created when print is called: internally to the System.out PrintWriter and the stream stack that it wraps,
each String object may (or may not) have a distinct char[] object inside it,
it is possible that the operations on s could be optimized away, since they actually have no effect on the output of the program (!!),
when the application is called, it will be passed a String[] argument, potentially populated with multiple String, and (finally),
an arbitrary number of objects will be created during JVM bootstrapping and class loading ... prior to the application starting.
So, depending on what objects you count, how you count them, and the other assumptions that you make, the answer could be some number from zero to a very large number of objects.
Note: the normal quiz answer for this would be "2 Strings are created", but as you can see the answer is a lot more complicated than that.
Note 2: the concat and toLowerCase methods do NOT create strings in the string pool. In fact, the only String operation that puts strings into the pool is intern. (It is easy to verify this experimentally, or by reading the Java class library source code.)
String in java is a immutable type.
s.concat(" Tendulkar");
s.toLowerCase();
these 2 lines return 2 distinct strings and doesn't affect the original string.
In java String is considered as immutable which means that it cannot be changed once its created, so if you count how many you have, on the first line you declared the first one, when you did s.concat("SE 6") you created a new object, and finally s.toLowerCase() created the 3rd object, therefore 3 string objects are created.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
I have a little/huge problem with String comparison in Java, I want to compare two Strings and .equals([...]) does not give me the correct result.
I also tried the following: ==, .compareTo([...]), .trim(), .equalsIgnoreCase([...]), creating a Collator with default Locale and using [collator].compare.
(All fail to work)
The first String comes from an already created object (the content of the string is from a database), the second String comes from a newly created object (but has been passed to a method), the content of this String is from the same database.
I am pretty clueless what to do now, the last thing I'd try is to convert it to some number (i.e. hex).
I already tried to write both Strings to console and manually look for differences, but there is none...
Code is this:
public static Lagerplatz hinzufuegen(Lagerplatz lagerplatz) {
boolean neu = true;
if (lagerplaetze.isEmpty()) {
lagerplaetze.add(lagerplatz);
System.out.println(lagerplatz.getBezeichnung() + " erstmalig hinzugefügt!");
}
for (int i = 0; i < lagerplaetze.size(); i++) {
System.out.println("'" + lagerplatz.getBezeichnung() + "'" + " - " + "'"
+ lagerplaetze.get(i).getBezeichnung() + "'");
if (lagerplatz.getBezeichnung().equalsIgnoreCase(lagerplaetze.get(i).getBezeichnung())) {
neu = false;
}
}
if (neu) {
lagerplaetze.add(lagerplatz);
System.out.println(lagerplatz.getBezeichnung() + " hinzugefügt!");
}
return lagerplatz;
}
The if-part with (lagerplaetze.isEmpty()) does work, after the first one is added it should check if the Lagerplatz (at least the name of it) is already in the lagerplaetze-ArrayList, if so then don't add, if not add.
Stepping through it revealed that the objects are correctly referenced...
Thanks very much in advance, and sorry if this question has been answered already but I can't find a helping answer under all these questions...
EDIT1: Normalizing does not help in this case, "umlaute" (german ä, ö or ü) are not causing the problem...
Converting the String to a byte[] and converting this byte-array to String like:
(Arrays.toString(lagerplatz.getBezeichnung().getBytes()).equalsIgnoreCase(
Arrays.toString(lagerplaetze.get(i).getBezeichnung().getBytes())))
and then comparing it does also not solve the problem, the bytes of the two strings are exactly the same: '[72, 55, 48]' - '[72, 55, 48]'
EDIT2: The problem is not with the String comparison, it is because the variables of the class "Lagerplatz" are static, they were replaced each time the loop is entered...
Maybe delete this question?
The only time two strings that look exactly the same but equals() does not result in true is when the unicode composition is different.
For example one can compose the A umlaut (Ä) with a single character: \u00C4
Or with a combination of the A character and the dots (the dieresis character ¨): \u0041\u0308
In essence, you are using two unicode characters for one letter. Because equals() compares characters, the form with dieresis is not equals to the form without.
To overcome this problem, one must decompose each string to a canonical form before comparison.
In Java one can create such a canonical form like this:
java.text.Normalizer.normalize("Your String", java.text.Normalizer.Form.NFD);
Once normalized, equals() will work as expected.
Obviously, since you didn't provide any data, this answer may or may not match your problem.
In any case, you might want to normalize all Strings in some form and then use a Set as data structure, not a list.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I need to use StringTokenizer to search through a string, and if they find this two words in the string, they will print "Yes.", if not, it'll print "No."
These two words are "eat", and "yet", and the string is "Did you eat yet?"
If it finds both words in that string it's suppose to print out yes, and if not, it's suppose to print out no. I have no idea how to do this. If you do, then please help.
StringTokenizer st = new StringTokenizer("Did you eat yet?");
This is how you initialize a StringTokenizer. Then your implementation should use the .hasMoreTokens() method to step through the tokens and check if they are equal to the words you are searching for.
Not sure why would want to use this method however, as..
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
From the documentation at http://docs.oracle.com/javase/7/docs/api/java/util/StringTokenizer.html
As others have suggested, using StringTokenizer is discouraged and in this case is over complicating the procedure in the first place.
Getting familiar with the Java String class is the right start. Here we find it's possible to determine if a string contains() the target string with yourString.contains(yourSubString).
You can combine this with another call to contains() in a conditional with...
if (yourString.contains(someSubString) &&
yourString.contains(someOtherSubString)) { ... }