How to convert char[] to string? - java

I have a question in this case how to convert char[] to string?(Must explicitly convert the char[] to a String) sorry being a novice programmer i am asking this.
String str3 = "Dad saw I was Playing";
System.out.println(str3.toCharArray() + "\n" + str3.toLowerCase() );
System.out.println(str3.toCharArray());
Output:
[C#1034bb5 //this is what I am getting for first str3.tochararray(),how to resolve this?
dad saw i was playing
Dad saw I was Playing

You can use Arrays.toString(char[]) (or create your own method if you prefer a different formatting). Something like,
String str3 = "Dad saw I was Playing";
System.out.println(Arrays.toString(str3.toCharArray()));

System.out.println(str3.toCharArray() + "\n" + str3.toLowerCase() );
This first calls toString over CharArray which outputs [C#1034bb5 and then append it to the rest of the string and print.
System.out.println(str3.toCharArray()); -- This calls the overridden method in PrintStream class which can interpret char array and print it.
You can explicitly convert your char array to string and print.

Related

Why can't I replace \n in a given String?

I found the question here before but somehow I can't see what I'm doing wrong. So I have a given String that looks something like this:
"Some text here\n\nsome more text here"
And I want to remove the linebreaks and display the Text in a TextView. I tried using String.replaceAll:
String newString = oldString.replaceAll("\\n", " ");
But that didn't change anything in the text. However,
oldString.contains("\\n"); returns true. What am I doing wrong?
edit:
I'm sorry, I know, oldString doesn't change. The problem is that, if I print oldString and newString they're exactly the same even though it says that oldString does contain a "\n".
This is my code:
Log.d(TAG, "contains: " + str.contains("\\n"));
Log.d(TAG, "old: " + str);
str = str.replaceAll("\\n", " ");
Log.d(TAG, "new: " + str);
And this is what I get:
contains: true
old: Vorgang nicht möglich\n\nBitte Karte entnehmen
new: Vorgang nicht möglich\n\nBitte Karte entnehmen
UPDATE
Thanks to Shivanshu Verma, I tried str.replace("\\n"" "); instead of str.replaceAll("\\n", " "); and that works! Does anybody know, why I can't use replaceAll() here?
Strings in Java are immutable and as such the new string with the replacements is stored in newString, not oldString.
EDIT
I see now that your issue was not actually related to Java String immutability but rather the difference between replace() and replaceAll(). The difference between these is that replaceAll() takes in a regex as the first argument, which will then replace any matches with the second argument, whereas replace() simply takes in a CharSequence (of which String is an implementation) and will replace exact matches with the second argument.
In your case, I think your original String had the newline characters escaped:
String str = "Vorgang nicht möglich\\n\\nBitte Karte entnehmen";
which meant that the String didn't actually contain newline characters at all; it contained literally "\n". This would mean that:
str.replaceAll("\\n", " ");
will resolve the first argument to a regex and replace newline characters (of which there were none), and:
str.replace("\\n", " ");
will replace exact matches of "\n". It's also worth noting that as others have pointed out contains() also doesn't take in a regex, which is why running:
oldString.contains("\\n");
returned true.
Your code works perfectly fine.
This test will pass without any error:
#Test
public void testReplaceAll() {
String newString = "line1\nline2\nline3".replaceAll("\\n", " ");
assertThat(newString).isEqualTo("line1 line2 line3");
assertThat(newString).doesNotContain("\\n");
}
try to Replace() method instead of ReplaceAll()
String newString = oldString.replace("\\n", " ");
may be it work for u
String newString = oldString.replace("\n", " ");

Converting an integer and a character to a string in java

I'm trying to create a string comprised of a single letter, followed by 4 digits e.g. b6789. I'm getting stuck when I try to convert a character, and integer to one String. I can't use toString() because I've overwritten it, and I assume that concatenation is not the best way to approach it? This was my solution, until I realised that valueof() only takes a single parameter. Any suggestions? FYI - I'm using Random, because I will be creating multiples at some point. The rest of my code seemed irrelevant, and hence has been omitted.
Random r = new Random();
Integer numbers = r.nextInt(9000) + 1000;
Character letter = (char)(r.nextInt(26) + 'a');
String strRep = String.valueOf(letter, numbers);
I think they mean for you not to use concatenation with + operator.
Rather than that, there's a class called StringBuilder which will do the trick for you. Just create an empty one, append anything you need on it (takes Objects or primitives as arguments and does all the work for you), and at the end, just call at its "toString()" method, and you'll have your concatenated String.
For example
StringBuilder sb = new StringBuilder();
sb.append("Foo");
sb.append(123);
return sb.toString();
would return the string Foo123
you can use:
Character.toString(char)
which is
String.valueOf(char)
in reality which also works.
or just use
String str = "" + 'a';
as already mentioned but not very efficient as it is
String str = new StringBuilder().append("").append('a').toString();
in reality.
same goes for integer + string or char + int to string. I think your simpliest way would be to use string concatenation
Looks like you want
String.valueOf(letter).concat(numbers.toString());

Character Concatenation Resulting in Numerical Output [duplicate]

This question already has answers here:
In Java, is the result of the addition of two chars an int or a char?
(8 answers)
Closed 9 years ago.
In a programming language called Java, I have the following line of code:
char u = 'U';
System.out.print(u + 'X');
This statement results in an output like this:
173
Instead of
UX
Am I missing something? Why isn't it outputing 'UX'? Thank you.
Because you are performing an addition of chars. In Java, when you add chars, they are first converted to integers. In your case, the ASCII code of U is 85 and the code for X is 88.
And you print the sum, which is 173.
If you want to concatenate the chars, you can do, for example:
System.out.print("" + u + 'X');
Now the + is not a char addition any more, it becomes a String concatenation (because the first parameter "" is a String).
You could also create the String from its characters:
char[] characters = {u, 'X'};
System.out.print(new String(characters));
In this language known as Java, the result of adding two chars, shorts, or bytes is an int.
Thus, the integer value of U (85) is added to the integer value of X (88) and you get an integer value of 173 (85+88).
To Fix:
You'll probably want to make u a string. A string plus a char will be a string, as will a string plus a string.
String u = "U"; // u is a string
System.out.print(u + 'X'); // string plus a char is a string
String u = "U";
System.out.print(u + "X");
instead of char type use String class or StringBuilder class
Another way to convert one of the characters to a string:
char u = 'U';
System.out.print(Character.toString(u) + 'X');
This way could be useful when your variable is of type char for a good reason and you can't easily redeclare it as a String.
That "language called Java" bit amused me.
A quick search for "java concatenate" (which I recommend you do now and every time you have a question) revealed that most good Java programmers hate using + for concatenation. Even if it isn't used numerically when you want string concatenation, like in your code, it is also slow.
It seems that a much better way is to create a StringBuffer object and then call its append method for each string you want to be concatenated to it. See here: http://www.ibm.com/developerworks/websphere/library/bestpractices/string_concatenation.html

Java - accessing characters in a string in a 2D-array-like manner?

Is there a more or less easy way (without having to implement it all by myself) to access characters in a string using a 2D array-like syntax?
For example:
"This is a string\nconsisting of\nthree lines"
Where you could access (read/write) the 'f' with something like myString[1][12] - second line, 13th row.
You can use the split() function. Assume your String is assigned to variable s, then
String[] temp = s.split("\n");
That returns an array where each array element is a string on its own new line. Then you can do
temp[1].charAt(3);
To access the 3rd letter (zero-based) of the first line (zero-based).
You could do it like this:
String myString = "This is a string\nconsisting of\nthree lines";
String myStringArr[] = myString.split("\n");
char myChar = myStringArr[1].charAt(12);
To modify character at positions in a string you can use StringBuffer
StringBuffer buf = new StringBuffer("hello");
buf.insert(3, 'F');
System.out.println("" + buf.toString());
buf.deleteCharAt(3);
System.out.println("" + buf.toString());
Other than that splitting into a 2D matrix should be self implemented.
Briefly, no. Your only option is to create an object that wraps and interpolates over that string, and then provide a suitable accessor method e.g.
new Paragraph(myString).get(1,12);
Note that you can't use the indexed operator [number] for anything other than arrays.

string to char array, showing silly characters

It is a really simple question but I need an another eye to look at my code:
String strtr = "iNo:";
char[] queryNo = strtr.toCharArray();
System.out.println(queryNo + " =this is no");
and the output is:
[C#177b4d3 =this is no
What are these characters, do you have any idea?
That's how toString() is implemented for arrays.
The [C denotes that is a char array, 177b4d3 is its hashcode.
You may want to look at
System.out.println(Arrays.toString(queryNo) + " =this is no");
if you want to see your original String again, you need this:
System.out.println((new String(queryNo)) + " =this is no");
Arrays do not override toString(), it is inherited from Object.toString as
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
you are printing the object
queryno, as queryno is a character array of on dimension and java is an object oriented language which holds every thing in the form of classes it gives the class name [C to your array where [ denotes total dimension and C denotes character type of array, Rest is the hashcode of the object.
You are trying to print the array and that is the reason you get gibberish. Try using Arrays.toString(queryNo) and you will see what you expected.

Categories

Resources