I see a program to reverse a string
public class ReverseName{
public static void main(String[]args)
{
String name=args[0];
String reverse=new StringBuffer(name).reverse().toString();
System.out.println(reverse);
}
}
so what is new StringBuffer(name).reverse().toString(); all about?
String reverse=new StringBuffer(name).reverse().toString();
Let's break this down.
new StringBuffer(name)
First off we create a new StringBuffer (I'd have used StringBuilder as we don't need thread safety) with the contents of name. This just allows a more peformant way to append strings but here it's used for the next part.
.reverse()
This calls the reverse method on the StringBuffer which returns a reversed StringBuffer.
.toString();
Finally this is turned back into a String.
You can split that into 3 lines for understanding
StringBuffer reverseBuffer = new StringBuffer(name); // Creating new StringBuffer object
reverseBuffer = reverseBuffer.reverse(); //Reversing the content using StringBuffer
String reverse = reverseBuffer.toString(); // Converting StringBuffer to String and saving in reverse
just a StringBuffer object reversing a string
You instantiate the StringBuffer object with the "name" String object , then reverse it.
From the JAVA API
public StringBuffer reverse()
Causes this character sequence to be replaced by the reverse of the sequence. If there are any surrogate pairs included in the sequence, these are treated as single characters for the reverse operation. Thus, the order of the high-low surrogates is never reversed. Let n be the character length of this character sequence (not the length in char values) just prior to execution of the reverse method. Then the character at index k in the new character sequence is equal to the character at index n-k-1 in the old character sequence.
Note that the reverse operation may result in producing surrogate pairs that were unpaired low-surrogates and high-surrogates before the operation. For example, reversing "\uDC00\uD800" produces "\uD800\uDC00" which is a valid surrogate pair.
Returns:
a reference to this object.
Since:
JDK1.0.2
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuffer.html#reverse%28%29
Actually String is an immutable class, that means once object of String is created its contents cannot be modified. Therefore we use StringBuffer to construct strings. In above example, object of StringBuffer is created with content name, String in name is reversed in same object of StringBuffer(as it is mutable). Again converted to String object and assigned that object to reverse object reference.
Related
I am reading response from TCP call and I have to read chars only. Reading each char takes too much time so I am creating array with maximum number the response might be. Problem in this approach that response length is less and array size is big. While converting that into String its also using those blank chars which were not used while reading response because of that its writing "NUL" into log file.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class TestArrayToString {
public static void main(String[] args) throws IOException {
char[] chars = new char[5];
chars[0] = 'K';
chars[1] = 'S';
chars[2] = 'H';
String s = new String(chars);
System.out.println(s);
FileWriter fw = new FileWriter(new File("C://projects//test//test.log"));
fw.write(s);
fw.flush();
fw.close();
}
}
Output
Is there any possibility to remove that NUL while writing.
Arrays are objects. When they are initialized (instantiated), each element of the array is initialized to their default values. For example, primitive numeric values are initialized to the number 0. Objects are initialized by default to NULL. Character primitives or char are initialized to Unicode value 0 (\U0000) which happens to be the null character.
Your code is initializing an array of five chars. Only the first three elements are set with new character values. The last two still contain default values.
To fix this, you either need to create a smaller array, or only convert to String characters containing not null values. An easy way to do this is by trimming. Something like this should work:
char[] chars = new char[5];
...
String s = String.valueOf(chars).trim();
UPDATE
Another added benefit to this solution is avoiding creating a new String for repeated values.
String s = new String(chars); // BAD
String s = String.valueOf(chars); // Preferred
The preferred answer only creates a new String if the value represented by the array of characters is not present in the String pool. If it is, it uses the already existing String. The String copy constructor creates a duplicate String (it disregards the String pool).
I have a string which is :
1|name|lastname|email|tel \n
2|name|lastname|email|tel \n
I know that I have to use a loop to display all lines but the problem is that in my assignment
I can't use arrays or other classes than String and System.
Also I would like to sort names by ascending order without using sort method or arrays.
Do I have to use compareTo method to compare two names ?
If that's the case, how do I use compareTo method to sort names.
For example, if compareTo returns 1, that means that the name is greater than the other one. In that case how do I manage the return to sort name properly in the string ?
To display all substrings of the string as in the example, you can just go through all characters one by one and store them in a string. Whenever you hit a delimiter (e.g. | or \n), print the last string.
Here's a thread on iterating through characters of a string in Java:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
If you also need to sort the names in ascending order without an array, you will need to scan the input many times - sorting N strings takes at least N*log(N) steps. If this is a data structure question, PriorityQueue should do the trick for you - insert all substrings and then pop them out in a sorted fashion :)
building on the previous answer by StoneyKeys, since i do not have the privilege to comment, you can use a simple if statement that when the char is a delimiter, System.out.println() your previous scanned string. Then you can reset the string to an empty string in preparation for scanning the next string.
In java, there are special .equals() operators for strings and chars so when you won't be using == to check strings or char. Do look into that. To reset the value of string just assign it a new value. This is because the original variable points at a certain string ie "YHStan", by making it point at "", we are effectively "resetting" the string. ie scannedstr = "";
Please read the code and understand what each line of code does. The sample code and comments is only for your understanding, not a complete solution.
String str ="";
String value = "YH\nStan";
for (int i=0; i <value.length(); i++) {
char c = value.charAt(i);
String strc = Character.toString(c);
//check if its a delimiter, using a string or char .equals(), if it is print it out and reset the string
if (strc.equals("\n")) {
System.out.println(str);
str ="";
continue; // go to next iteration (you can instead use a else if to replace this)
}
//if its not delimiter append to str
str = str +strc;
//this is to show you how the str is changing as we go through the loop.
System.out.println(str);
}
System.out.println(str); //print out final string result
This gives a result of:
Y
YH
YH
S
St
Sta
Stan
Stan
I'd like to know for character concatenation in Java - which one of the below method would be better for readability, maintenance and performance - either 'char array' or 'string builder'.
The method has to take the first letter from both the strings, append and return it.
Eg:
Input 1: ABC Input 2: DEF -> method should return AD.
using string builder:
private String getString(String str1, String str2) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(str1.charAt(0));
stringBuilder.append(str2.charAt(0));
return stringBuilder.toString();
}
using char array:
private String getString(String str1, String str2) {
char[] charArray = new char[2];
charArray[0] = str1.charAt(0);
charArray[1] = str2.charAt(0);
return String.valueOf(charArray);
}
StringBuilder is just a wrapper around a char[], adding functionality like resizing the array as necessary; and moving elements when you insert/delete etc.
It might be marginally faster to use the char[] directly for some things, but you'd lose (or have to reimplement) a lot of the useful functionality.
charArray is good in term of Performance and readability too but it hard to maintain the code like this. It can cause the error like Null pointer. You just need to add the null check with char[] code.
On the other side StringBuffer internally use the char. So, char is better here and also by doing this we are not creating an Object. Memory point of view. It's good not to create that one.
If you review the source code for StringBuilder, you will find that internally it uses a char[] to represent the buffered string. So both versions of your code are doing very similar things. However, I would vote for using StringBuilder, because it offers an API which can much more than the plain char[] which sits inside its implementation.
I have two strings and I am trying to copy one into another. How I can copy character by character a string into another in Java?.
Strings are immutable objects in Java, which means that after they are instantiated, they will not change internal state. Instead, if you want to modify a String, you will always get a new String.
Now, to your question. If you want to copy a String chararcter by character this is highly inefficient, since you would create a new String object each time you copy a character. Luckily, there are plenty of other options.
String a = "a";
String b = "b";
String c = a + b; // "ab"
String d = a.concat(b); // "ab"
If you simply want to copy a String, you can do the following:
String e = a; "a"
Why does that work? As stated earlier, Strings a immutable, thus a new String with the same content is created. You can think of it as String e = new String(a), which is slightly less performant (and therefore an antipattern), but also works.
How should i declare a char array whose size ranges from 1 to 100 and I cannot make an array of size 100 because i have to make many arrays.
My input is:
"bjomboleji";
"bnmjsjbfhaihfaihfga";
"zbihgfbjbnsdfbnbfkj";
"bnxbz";
and i have to check the common occurence of characters.
Use ArrayList for dynamic array.
List<Chracter> array = new ArrayList<Chracter>();
Use a String to assign the value, then use toCharArray to convert to an array (if you really need a character array)
Use a StringBuilder. It is a "mutable sequence of characters."
This is a better solution than a List<Character> as it avoids the need to create Character objects from char primitives.
This is a better choice than manipulating a String as String objects are immutable and manipulation results in additional objects being created.
Variable length char is basically interface CharSequence which is implemented by String, StringBuilder, StringBuffer. So you can use any of it for variable char array.
To my understanding you need to count occurrences of a character in a string.If that's the case here is an example. there is no need to convert it to char array
public class Test {
public static void main(String[] args) {
String x="dhakjkfhajfhuagjkadmnfd";
String y="tskashguadmnsdm,as";
String Check_Character="s";
//Availability
System.out.println("X has Check_Character :"+x.contains(Check_Character)); //false
System.out.println("Y has Check_Character :"+y.contains(Check_Character));//true
//Number of occurrences
System.out.println("X has Check_Character :"+((x+" ").split(Check_Character).length-1)+" : times");//0 times
System.out.println("Y has Check_Character :"+((y+" ").split(Check_Character).length-1)+" : times");//4times
}
}
Otherwise you can use a list instead of an array or use this.
String z="dhakjkfhajfhuagjkadmnfd";
char c[]=z.toCharArray();