What you are trying to achieve is already implemented in CryptoJS. From the documentation:
You can convert a WordArray object to other formats by explicitly calling the toString method and passing an encoder.
var hash = CryptoJS.SHA256("Message");
alert(hash.toString(CryptoJS.enc.Base64));
alert(hash.toString(CryptoJS.enc.Hex));
Honestly I have no idea why you want to implement that yourself… But if you absolutely need to do it «manually» in the 2 steps you mentioned, you could try something like this:
function wordToByteArray(wordArray) {
var byteArray = [], word, i, j;
for (i = 0; i < wordArray.length; ++i) {
word = wordArray[i];
for (j = 3; j >= 0; --j) {
byteArray.push((word >> 8 * j) & 0xFF);
}
}
return byteArray;
}
function byteArrayToString(byteArray) {
var str = "", i;
for (i = 0; i < byteArray.length; ++i) {
str += escape(String.fromCharCode(byteArray[i]));
}
return str;
}
var hash = CryptoJS.SHA256("Message");
var byteArray = wordToByteArray(hash.words);
alert(byteArrayToString(byteArray));
The wordToByteArray
function should work perfectly, but be aware that byteArrayToString
will produce weird results in almost any case. I don’t know much about encodings, but ASCII only uses 7 bits so you won’t get ASCII chars when trying to encode an entire byte. So I added the escape
function to at least be able to display all those strange chars you might get.
I’d recommend you use the functions CryptoJS has already implemented or just use the byte array (without converting it to string) for your analysis.
Answer by Eva Zavala
What you are trying to achieve is already implemented in CryptoJS. From the documentation:,You can convert a WordArray object to other formats by explicitly calling the toString method and passing an encoder.,I’d recommend you use the functions CryptoJS has already implemented or just use the byte array (without converting it to string) for your analysis.,
1
First question: why do you need this? There’s almost certainly a better way to achieve whatever you’re trying to accomplish.
– Blazemonger
Aug 9 ’12 at 18:06
You can convert a WordArray object to other formats by explicitly calling the toString method and passing an encoder.
var hash = CryptoJS.SHA256("Message");
alert(hash.toString(CryptoJS.enc.Base64));
alert(hash.toString(CryptoJS.enc.Hex));
Honestly I have no idea why you want to implement that yourself… But if you absolutely need to do it «manually» in the 2 steps you mentioned, you could try something like this:
function wordToByteArray(wordArray) {
var byteArray = [], word, i, j;
for (i = 0; i < wordArray.length; ++i) {
word = wordArray[i];
for (j = 3; j >= 0; --j) {
byteArray.push((word >> 8 * j) & 0xFF);
}
}
return byteArray;
}
function byteArrayToString(byteArray) {
var str = "", i;
for (i = 0; i < byteArray.length; ++i) {
str += escape(String.fromCharCode(byteArray[i]));
}
return str;
}
var hash = CryptoJS.SHA256("Message");
var byteArray = wordToByteArray(hash.words);
alert(byteArrayToString(byteArray));
Answer by Thalia Cantu
Base64.stringify wants a wordArray as the input, not a string. Do that conversion first.,How to get a WordArray from Buffer, this buffer may be created by s.readFileSync(chunkLocalPath),@gamelife 1314 CryptoJS.enc.Hex.parse(),It’s not work and throw error
crypto-js.js:789 Uncaught TypeError: wordArray.clamp is not a function
$signStr = base64_encode(hash_hmac('SHA1', 'msg', $secret_key, true).'msg');
Answer by Landon Payne
var encrypt=function (type,val,salt) {
if(!val)
{
return ""
}
var arr=["Base64","MD5","SHA-1","SHA-256","SHA-512","SHA-3","RIPEMD-160"];
var arrFunc=[BASE64.encoder,CryptoJS.MD5,CryptoJS.SHA1,CryptoJS.SHA256,CryptoJS.SHA512,CryptoJS.SHA3,CryptoJS.RIPEMD160]
var arrSalt=["AES","TripleDES","DES","Rabbit","RC4","RC4Drop"];
var arrSaltFunc=[CryptoJS.AES.encrypt,CryptoJS.TripleDES.encrypt,CryptoJS.DES.encrypt,CryptoJS.Rabbit.encrypt,CryptoJS.RC4.encrypt,CryptoJS.RC4Drop.encrypt];
var index=arr.indexOf(type);
if(index>-1)
{
return arrFunc[index](val).toString();
}
index=arrSalt.indexOf(type);
if(index>-1)
{
return arrSaltFunc[index](val,salt).toString();
}
return val;
}
Answer by Gatlin Alexander
Strings containing Emojis,Stack Overflow: How do you get a string to a character array in JavaScript? ,
Convert Array-like to True Array in JavaScript
,
String Trim in JavaScript
const string = 'word';
// Option 1
string.split('');
// Option 2
[...string];
// Option 3
Array.from(string);
// Option 4
Object.assign([], string);
// Result:
// ['w', 'o', 'r', 'd']
Answer by Celia Compton
Write a JavaScript function to split a string and convert it into an array of words.,See the Pen JavaScript Split a string and convert it into an array of words — string-ex-3 by w3resource (@w3resource) on CodePen.,Previous: Write a JavaScript function to check whether a string is blank or not.
Next: Write a JavaScript function to extract a specified number of characters from a string.,Because of certain maintenance issues of our servers and financial constraints, we are closing our commenting system for the time being. We may resume that in the near future.
HTML Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Split a string and convert it into an array of words.</title>
</head>
<body>
</body>
</html>
JavaScript Code:
string_to_array = function (str) {
return str.trim().split(" ");
};
console.log(string_to_array("Robin Singh"));
Sample Output:
["Robin","Singh"]
Answer by Alice Mendez
Most frequent word in an array of strings,Time complexity : O(n),A Time Complexity Question,Given an array of words find the most occurring word in itExamples:
Given an array of words find the most occurring word in it
Examples:
Input : arr[] = {"geeks", "for", "geeks", "a",
"portal", "to", "learn", "can",
"be", "computer", "science",
"zoom", "yup", "fire", "in",
"be", "data", "geeks"}
Output : Geeks
"geeks" is the most frequent word as it
occurs 3 times
Output
The word that occurs most is : geeks
No of times: 3
Output
geeks
Output
3
geeks
Output
geeks
Answer by Guadalupe Howard
var input = 'john smith~123 Street~Apt 4~New York~NY~12345';
var fields = input.split('~');
var name = fields[0];
var street = fields[1];
Answer by Alden Briggs
str_word_count() — Return information about words used in a string,count_chars() — Return information about characters used in a string,str_split — Convert a string to an array,explode() — Split a string by a string
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
[5] =>
[6] => F
[7] => r
[8] => i
[9] => e
[10] => n
[11] => d
)
Array
(
[0] => Hel
[1] => lo
[2] => Fri
[3] => end
)
Dont think so…but you could break the word into bytes to use that function then concatenate the strings…assuming the word is in byte order, otherwise I think you’d have to force it in some manner anywasy since a character is a byte…
________________________________________________________
Use the rating system, otherwise its useless; and please don’t forget to tip your waiters!
using LV 2010 SP 1, Windows 7
________________________________________________________
You don’t really need a new function, since a simple Type Cast will do the trick:
Message Edited by smercurio_fc on 04-25-2008 12:50 PM
Author
smercurio,
I tried doing that with no success.
BTW how do you attach an image to a post?
Thanks
FredTest
Try again Fred, and look at the value you have in your word x4CD3 when it should be x4C3D.
________________________________________________________
Use the rating system, otherwise its useless; and please don’t forget to tip your waiters!
using LV 2010 SP 1, Windows 7
________________________________________________________
The red dot on the Byte Array to String function tells me that there datatype coercion going on. You need to set the datatype of the array elements to U8. They’re probably set to the default of I32. Note: This is just for the upper array. The other array should obviously be U16.
To attach an image to the post:
- Get the image. I use Code Capture Tool.
- Paste the path to the file in the textbox in the «Attachment» section that appears below the message creation box.
- Submit the post. (Note: If you preview the post, the attachment gets lost and you’ll need to specify it again.)
If you then want to insert the image in the body of the post:
- Go over to the «Options» menu that appears on the right just above the message body. This is a dropdown menu. Select «Edit».
- When you get the edit screen you’ll see the URL for your image, as it’s been uploaded to the NI servers.
- Right-click on the URL and select «copy link» (or something to that effect, depending on your browser).
- Where you want to embed the picture click on the «Insert an image» button (yellow square with a mountain) in the toolbar right above the message entry area.
- Paste in the URL.
- Re-submit the post.
Message Edited by smercurio_fc on 05-07-2008 02:40 PM
@TWGomez wrote:
Try again Fred, and look at the value you have in your word x4CD3 when it should be x4C3D.
That won’t fix it. The problem is with the datatype of the array elements, as I indicated in my response.
All you need is a typecast (unless you have issues with byte order).
Message Edited by altenbach on 05-07-2008 12:52 PM
altenbach wrote:
… (unless you have issues with byte order).
If you want little endian, use «flatten to string» as follows:
Message Edited by altenbach on 05-07-2008 12:56 PM
altenbach said
All you need is a typecast (unless you have issues with byte order).
Quite true. I was just showing how the typecast would give you the same U8 array that the user was initially trying with the Byte Array to String function.
Message Edited by smercurio_fc on 05-07-2008 03:01 PM
В этом посте мы обсудим, как преобразовать массив символов в строку в Java. Должна быть выделена новая строка, представляющая последовательность символов, содержащихся в массиве char. Поскольку строка неизменяема в Java, последующая модификация массива символов не влияет на выделенную строку.
1. Использование конструктора строк
Самое простое решение — передать массив символов в конструктор String. Конструктор String внутренне использует Arrays.copyOf()
чтобы скопировать содержимое массива символов.
// Преобразование массива символов в строку в Java class Main { public static void main(String[] args) { char[] chars = {‘T’, ‘e’, ‘c’, ‘h’, ‘i’, ‘e’, ‘ ‘, ‘D’, ‘e’, ‘l’, ‘i’, ‘g’, ‘h’, ‘t’}; String string = new String(chars); System.out.println(string); } } |
Скачать Выполнить код
результат:
Techie Delight
2. Использование String.valueOf()
или же String.copyValueOf()
метод
Мы можем инкапсулировать вызов конструктора строки, используя String.valueOf()
или же String.copyValueOf()
который внутри делает то же самое.
// Преобразование массива символов в строку в Java class Main { public static void main(String[] args) { char[] chars = {‘T’, ‘e’, ‘c’, ‘h’, ‘i’, ‘e’, ‘ ‘, ‘D’, ‘e’, ‘l’, ‘i’, ‘g’, ‘h’, ‘t’}; String string = String.copyValueOf(chars); System.out.println(string); } } |
Скачать Выполнить код
результат:
Techie Delight
3. Использование StringBuilder
Другой вероятный способ преобразования массива символов в строку — использование StringBuilder
в Java. Идея состоит в том, чтобы перебирать символы и добавлять каждый символ в StringBuilder
. Наконец, позвоните в toString()
метод на StringBuilder
при повторении всех символов.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Преобразование массива символов в строку в Java class Main { public static void main(String[] args) { char[] chars = {‘T’, ‘e’, ‘c’, ‘h’, ‘i’, ‘e’, ‘ ‘, ‘D’, ‘e’, ‘l’, ‘i’, ‘g’, ‘h’, ‘t’}; StringBuilder sb = new StringBuilder(); for (char ch: chars) { sb.append(ch); } String string = sb.toString(); System.out.println(string); } } |
Скачать Выполнить код
результат:
Techie Delight
4. Использование toString()
метод
(Не рекомендуется)
Здесь идея состоит в том, чтобы получить строковое представление указанного массива. Строковое представление состоит из списка элементов массива, заключенного в квадратные скобки ("[]"
), а все соседние элементы разделяются запятой, за которой следует пробел ", "
.
Мы можем легко избавиться от квадратных скобок, вызвав метод substring()
метод и запятая + пробел с помощью replaceAll()
метод.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.Arrays; // Преобразование массива символов в строку в Java class Main { public static void main(String[] args) { char[] chars = {‘T’, ‘e’, ‘c’, ‘h’, ‘i’, ‘e’, ‘ ‘, ‘D’, ‘e’, ‘l’, ‘i’, ‘g’, ‘h’, ‘t’}; String string = Arrays.toString(chars) .substring(1, 3*chars.length—1) .replaceAll(«, «, «»); System.out.println(string); } } |
Скачать Выполнить код
результат:
Techie Delight
Это все о преобразовании массива символов в строку Java.
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂
Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character “”. A character array can be converted to a string and vice versa. In the previous article, we have already discussed how to convert a string to a character array. In this article, we will discuss how to convert a character array to a string.
Illustrations:
Input 1 : char s[] = { ‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’ }
Output 1 : “geeksforgeeks”
Input 2 : char s[] = { ‘c’, ‘o’, ‘d’, ‘i’, ‘n’, ‘g’ }
Output 2 : “coding”
Methods:
- Using copyOf() method of Arrays class
- Using StringBuilder class
- Using valueOf() method of String class
- Using copyValueOf() method of String class
- Using Collectors in Streams
Now let us discuss each of the methods in detail alongside implementing them with help of a clean java program.
Method 1: Using copyOf() method of Array class
The given character can be passed into the String constructor. By default, the character array contents are copied using the Arrays.copyOf() method present in the Arrays class.
Example:
Java
import
java.util.*;
class
GFG {
public
static
String toString(
char
[] a)
{
String string =
new
String(a);
return
string;
}
public
static
void
main(String args[])
{
char
s[] = {
'g'
,
'e'
,
'e'
,
'k'
,
's'
,
'f'
,
'o'
,
'r'
,
'g'
,
'e'
,
'e'
,
'k'
,
's'
};
System.out.println(toString(s));
}
}
Output:
geeksforgeeks
Method 2: Using StringBuilder class
Another way to convert a character array to a string is to use the StringBuilder class. Since a StringBuilder is a mutable class, therefore, the idea is to iterate through the character array and append each character at the end of the string. Finally, the string contains the string form of the characters.
Example:
Java
import
java.util.*;
public
class
GFG {
public
static
String toString(
char
[] a)
{
StringBuilder sb =
new
StringBuilder();
for
(
int
i =
0
; i < a.length; i++) {
sb.append(a[i]);
}
return
sb.toString();
}
public
static
void
main(String args[])
{
char
s[] = {
'g'
,
'e'
,
'e'
,
'k'
,
's'
,
'f'
,
'o'
,
'r'
,
'g'
,
'e'
,
'e'
,
'k'
,
's'
};
System.out.println(toString(s));
}
}
Method 3: Using valueOf() method of String class
Another way to convert a character array to a string is to use the valueOf() method present in the String class. This method inherently converts the character array to a format where the entire value of the characters present in the array is displayed. This method generally converts int, float, double, char, boolean, and even object to a string. Here we will achieve the goal by converting our character array to string.
Example:
Java
import
java.util.*;
class
GFG {
public
static
String toString(
char
[] a)
{
String string = String.valueOf(a);
return
string;
}
public
static
void
main(String args[])
{
char
s[] = {
'g'
,
'e'
,
'e'
,
'k'
,
's'
,
'f'
,
'o'
,
'r'
,
'g'
,
'e'
,
'e'
,
'k'
,
's'
};
System.out.println(toString(s));
}
}
Method 4: Using copyValueOf() method of String class
The contents from the character array are copied and subsequently modified without affecting the string to be returned, hence this method also enables us to convert the character array to a string which can be perceived even better from the example provided below as follows.
Example:
Java
import
java.util.*;
class
GFG {
public
static
void
main(String[] args)
{
char
[] arr = {
'g'
,
'e'
,
'e'
,
'k'
,
's'
,
'f'
,
'o'
,
'r'
,
'g'
,
'e'
,
'e'
,
'k'
,
's'
};
String str = String.copyValueOf(arr);
System.out.print(str);
}
}
Method 5: Using Collectors in Streams
With the introduction of streams in java8, we straight away use Collectors in streams to modify our character input array elements and later uses joining() method and return a single string and print it.
Example:
Java
import
java.util.stream.Collectors;
import
java.util.stream.Stream;
class
GFG {
public
static
void
main(String[] args)
{
char
[] charr = {
'g'
,
'e'
,
'e'
,
'k'
,
's'
,
'f'
,
'o'
,
'r'
,
'g'
,
'e'
,
'e'
,
'k'
,
's'
};
String str = Stream.of(charr)
.map(arr ->
new
String(arr))
.collect(Collectors.joining());
System.out.println(str);
}
}