Kwert-soft.ru

IT Софт для ПК
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Char array to string java

Char array to string java

Java String To Char Array

String is just a staple of most programming languages. It represents a sequence of characters into one data structure. It is a very convenient way to store many types of things in memory or in the database. An array on the other hand is one of the most simple way to represent multiple values. It is simpler that Classes such as List or Set because it can also be found in older programming language such as C/C++ or Pascal. It is only natural that we sometimes want to convert a String into an array of Characters for easier manipulation later. Below are some ways on how we can Convert a String to Char Array in Java .

Convert String To Char Array Using toCharArray()

Fortunately, the String class has a built in function toCharArray() that can do this conversion for us. Here is the signature.
The Java documentation says that this function Converts this string to a new character array.. Further it states that it returns a newly allocated character array whose length is the length of this string and whose contents are initialized to contain the character sequence represented by this string. Consider the code below that uses this function.

We can even use this in String literal, because String literals are actually String instances.

To complete our example, try to guess the output of below code:

We get an array with size 3 having the first item as «D», the second as «o», and the third as «g». The output should be:

Convert String To Char Array Using Java 8 String.chars()

There are cool ways that we could solve this problem if we are using Java 8. Here is an example on how to convert using Java 8 and String’s chars() method.
This one does a lot of things in one go. But we still get an array of character in the end, which is what we want. The output would be:

If we look at the signature of chas() in Java documentation we will get:

It says that this returns a stream of int zero-extending thechar values from the sequence.

Convert String To Char Array Using Java 8 String.codePoints()

Another alternative in Java 8 is to use codePoints instead of chars() method. Everything else is similar:
The output should be the expected display:

If we look at the signature of codePoints() in Java documentation we will get:

It says that this returns a stream of code point values from the sequence.

Читать еще:  Java regexp substring

Convert String To Char Array Using Own Code

Just to exercise our brain, we can also implement our own solution to convert a String to an array of Character. See below code:

The first line is we created an array with size the same length as the String.

Then we copy each character from the String to the corresponding array element.
Putting it all together in an example, we have:

We use the function and pass the String «Apple» and we will have the following output:

Convert char array to String in Java

In this post, we will discuss how to convert char array to String in Java. A new String should be allocated that represents the sequence of characters contained in the char array. Since String is immutable in Java, the subsequent modification of the character array does not affect the allocated string.

1. Using String Constructor

The simplest solution is to pass the char array into the String constructor. The String constructor internally uses Arrays.copyOf() to copy the contents of the character array.

Output:

Techie Delight

2. String.valueOf() or String.copyValueOf()

We can encapsulate the String construtor call by using String.valueOf() or String.copyValueOf() which internally does the same thing.

Output:

Techie Delight

3. Using StringBuilder

Another plausible way of converting a char array to String is using StringBuilder in Java. The idea is to iterate over the characters and append each char to a StringBuilder. Finally, call toString() method on the StringBuilder when iterated over all chars.

Output:

Techie Delight

4. toString() + substring() + Regex

The idea here is to get a string representation of the specified array. The string representation consists of a list of the array’s elements, enclosed in square brackets ("[]") and all adjacent elements are separated by a comma followed by a space ", ".

We can easily get rid of the square brackets by calling substring() function, and comma + space by using replaceAll() method.

Output:

Techie Delight

(10 votes, average: 4.50 out of 5)
Loading.

Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP and many more popular programming languages.

Like us? Refer your friends and help us grow. Happy coding

Convert Character Array to String in Java

Last modified: October 14, 2019

I just announced the new Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2:

In the 9 years of running Baeldung, I’ve never, ever done a «sale».
But. we’ve also not been through anything like this pandemic either.
And, if making my courses more affordable for a while is going to help a company stay in business, or a developer land a new job, make rent or be able to provide for their family — then it’s well worth doing.
Effective immediately, all Baeldung courses are 33% off their normal prices!
You’ll find all three courses in the menu, above, or here.

Читать еще:  Jdbc java пример

1. Overview

In this quick tutorial, we’ll cover various ways to convert a character array to a String in Java.

2. String Constructor

The String class has a constructor that accepts a char array as an argument:

This is one of the easiest ways of converting a char array to a String. It internally invokes String#valueOf to create a String object.

3. String.valueOf()

And speaking of valueOf(), we can even use it directly:

String#copyValueOf is another method that’s semantically equivalent to the valueOf() method but was of any significance only in a first few Java releases. As of today, the copyValueOf() method is redundant and we don’t recommend using it.

4. StringBuilder‘s toString()

What if we want to form a String from an array of char arrays?

Then, we can first instantiate a StringBuilder instance and use its append(char[]) method to append all contents together.

Later, we’ll use the toString() method to get its String representation:

We can further optimize the above code by instantiating the StringBuilder of the exact length we need.

5. Java 8 Streams

With Arrays.stream(T[] object) method, we can open a stream over an array of type T.

Considering we have a Character array, we can use the Collectors.joining() operation to form a String instance:

The caveat with this approach is that we are invoking the valueOf() over each Character element and so it’ll be pretty slow.

6. Guava Common Base Joiner

Let’s say though that the string we need to create is a delimited string. Guava gives us a handy method:

Again, note that the join() method will only accept a Character array and not the primitive char array.

7. Conclusion

In this tutorial, we explored ways of converting a given character array to its String representation in Java.

As usual, all code examples can be found over on GitHub.

Copying Character Array To String In Java – Tutorial

in Java Tutorials Comments Off on Copying Character Array To String In Java – Tutorial

Java tutorial to copy character array to string. Here, we will discuss about the various methods of copying a character array to a string using. If you have any doubts leave a comment here at the end of the post.

  • Creating a string object based on the character array.
  • Adding character by character to an initially empty string.
  • Setting character by character into a string buffer.
  • Using the static method CopyValueOf() of string >Creating a String object based on the character array

This is the simplest way of copying a character array into a String.

For Example:

Output:

In the above example, we have an array of 5 characters (containing the letters h, i, m, m and u). Length of this array is 5 (as we have 5 characters).

Then we have created a String object by specifying the character array as argument to constructor. With this a new String is created with the characters of the character array. It means the new String will be of length 5 with the characters h,i,m,m and u at 0,1,2,3 and 4 locations respectively. The output confirms it.

Adding character by character to an (initially) empty string

Sample logic:

Output:

In this example, we have an empty string initially. And then, taken a loop that is repeated for N number of times where N is the number of characters in the array.

Each time (with each iteration i.e. from 0 th position to N-1 th position) a character is taken from the array and appended to the String. Then we have printed the string and its length. The resulting string will be “himani” and its length 6.

Setting character by character into a String Buffer

Sample Logic:

We cannot change the content of an existing String object. But we can change the content of a StringBuffer or StringBuilder object.

In the above example, we have taken a StringBuffer object that already contains some content. With the existing content, the length of the StringBuffer object is 11.

Then we have taken each character from the character array and stored in the locations 0,1,2,etc… it means, the letter ‘g’ (from 0 th location of the array) replaces ‘l’ (the 0 th letter in StringBuffer object) and ‘a’ replaces ‘e’, ‘n’ replaces ‘n’, ‘d’ replaces ‘g’, ‘h’ replaces ‘t’ and ‘i’ replaces ‘h’.

By the end of the for loop the replacements will be complete and the StringBuffer object contains “gandhiytext”. Then we have taken a substring of the StringBuffer object.

We have taken the first 6 letters of the StringBuffer object and left the remaining letters. So, by the time we go for printing, we will have “gandhi” in the StringBuffer object and its length will be 6.

Ссылка на основную публикацию
Adblock
detector