Python
There is no ordinary array in the python language, use the list class instead. It is very convenient to convert strings. Basically, all objects have corresponding built-in methods __repr__() to convert obj into the corresponding string, and the corresponding built-in function is repr().
>>> help(repr)
Help on built-in function repr in module builtins:repr(obj, /)
Return the canonical string representation of the object.
For many object types, including most builtins, eval(repr(obj)) == obj.
Example:
>>> a = [1,2,3,4] >>> b = [[1, 2],[3, 4],[5, 6]] >>> c = [[1, 2], [3, 4], [5, [7,8,9]]] >>> repr(a) '[1, 2, 3, 4]' >>> repr(b) '[[1, 2], [3, 4], [5, 6]]' >>> repr(c) '[[1, 2], [3, 4], [5, [7, 8, 9]]]'
One-dimensional list to string
.join() method + list comprehension (see as a simple version of loop traversal):
>>> a = [1, 2, 3, 4] >>> "[" + ",".join(str(elem) for elem in a) + "]" '[1,2,3,4]'
More Pythonic writing:
>>> a = [1,2,3,4] >>> ",".join(map(str,a)).join("[]") '[1,2,3,4]'
Two-dimensional list to string
>>> b = [[1,2],[3,4]] >>> ",".join(",".join(map(str,a)).join("[]") for a in b).join("[]") '[[1,2],[3,4]]'
Multidimensional list to string
You can customize a recursive function to simulate the implementation of __repr__():
>>> from typing import List >>> def List2Str(s): if not s: return '[]' pieces = [] for item in s: if isinstance(item, List): (List2Str(item)) else: (str(item)) return ','.join(pieces).join('[]') >>> a = [1, 2, 3, 4] >>> b = [[1, 2], [3, 4]] >>> c = [[1, 2], [3, 4], [5, [7, 8, 9]]] >>> List2Str(a) '[1,2,3,4]' >>> List2Str(b) '[[1,2],[3,4]]' >>> List2Str(c) '[[1,2],[3,4],[5,[7,8,9]]]'
For Python, there is actually no need to convert. You can directly use repr(), str(), and print() to process the list, and don’t care about what data type the list element is, which is very worry-free.
Golang
Go language does not have ready-made list and vector container classes, only arrays and slices, which can be printed directly, but separated by spaces:
package main import "fmt" func main() { a := []int{1, 2, 3, 4} b := [][]int{{1, 2}, {3, 4}, {5, 6, 7}} (a) (b) }
Output:
[1 2 3 4]
[[1 2] [3 4] [5 6 7]]
It is necessary to separate it with commas and replace it with (). This method can be used on any dimension array.
package main import ( "fmt" "strings" ) func main() { a := []int{1, 2, 3, 4} b := [][]int{{1, 2}, {3, 4}, {5, 6, 7}} str := ((a), " ", ",") (str) str = ((b), " ", ",") (str) }
Output:
[1,2,3,4]
[[1,2],[3,4],[5,6,7]]
For one-dimensional arrays, there are also methods similar to .join() in python:
package main import ( "fmt" "strings" ) func main() { a := []int{1, 2, 3, 4} str := (((a)), ",") (str) }
1D array traversal printing
package main import "fmt" func ArrayToString(arr []int) string { res := "[" for i := 0; i < len(arr); i++ { res += (arr[i]) //For the []int array, you can use (arr[i]) if i != len(arr)-1 { res += "," } } return res + "]" } func main() { arr := []int{1, 2, 3, 4, 5} (ArrayToString(arr)) }
Traversal printing of two-dimensional arrays
package main import "fmt" func Array2DToString(array [][]int) string { if len(array) == 0 { return "[]" } arr2str := func(arr []int) string { res := "[" for i, ar := range arr { res += (ar) if i != len(arr)-1 { res += "," } } return res + "]" } res := "[" for i, arr := range array { res += arr2str(arr) if i != len(array)-1 { res += "," } } return res + "]" } func main() { arr := [][]int{{1, 2}, {3, 4}, {5, 6, 7}} (Array2DToString(arr)) }
or:
package main import ( "fmt" "strings" ) func Array2DToString(array [][]int) string { if len(array) == 0 { return "[]" } arr2str := func(arr []int) string { res := "[" for i := 0; i < len(arr); i++ { res += (arr[i]) if i != len(arr)-1 { res += "," } } return res + "]" } res := make([]string, len(array)) for i, arr := range array { res[i] = arr2str(arr) } return (((res)), ",") } func main() { arr := [][]int{{1, 2}, {3, 4}, {5, 6, 7}} (Array2DToString(arr)) }
The above example code outputs all the compact form [1, 2, 3, 4]. If you like to have spaces such as [1, 2, 3, 4], you can use ", " instead of "," in the above code.
Java
Direct printing of one-dimensional containers
Java's data types are super rich, and it can even be said to be flooding. Container classes can be printed directly, but ordinary arrays cannot:
import .*; public class main { public static void main(String[] args) { int[] a = {1, 2, 3, 4}; (a); Integer[] b = {1, 2, 3, 4}; (b); List<Integer> c = (b); (c); Vector<Integer> d = new Vector<>(c); (d); } }
Output:
[I@123a439b
[;@7de26db8
[1, 2, 3, 4]
[1, 2, 3, 4]
Direct printing of 2D containers
import .*; public class main { public static void main(String[] args) { Integer[][] arrays = {{1, 2}, {3, 4}}; List<List<Integer>> list = new ArrayList<>(); for (Integer[] array1D : arrays) { (new ArrayList<>((array1D))); } Vector<Vector<Integer>> vector = new Vector<>(); for (Integer[] array1D : arrays) { (new Vector<>((array1D))); } (list); (vector); } }
Output:
[[1, 2], [3, 4]]
[[1, 2], [3, 4]]
Conversion of ordinary arrays
It is also very convenient. There are ready-made() functions available, and deepToString() should be used for two-dimensional and above arrays. It can be achieved without loop traversal. If necessary, please refer to the traversal implementation method in the go language above.
import .*; public class main { public static void main(String[] args) { Integer[] array1D = {1, 2, 3, 4}; Integer[][] array2D = {{1, 2}, {3, 4}}; int[][][] array3D = {{{1, 2}, {3, 4}}, {{11, 12}, {13, 14}}}; String str1 = (array1D); String str2 = (array2D); String str3 = (array3D); (str1); (str2); (str3); } }
Output:
[1, 2, 3, 4]
[[1, 2], [3, 4]]
[[[1, 2], [3, 4]], [[11, 12], [13, 14]]]
C++
C++98 started with vector containers, but in C++ neither container nor array can be printed directly.
The traversal method is basically the same as in golang:
Traversal of one-dimensional containers
1. to_string()
#include <vector> #include <sstream> #include <iostream> using namespace std; int main() { vector<int> v = {1, 2, 3, 4, 5}; string str = "["; for (int i = 0; i < (); ++i) { str += to_string(v[i]); if (i != () - 1) { str += ", "; } } str += "]"; cout << str << endl; return 0; }
2. stringstream
#include <vector> #include <sstream> #include <iostream> using namespace std; int main() { vector<int> v = {1, 2, 3, 4, 5}; stringstream ss; ss << "["; for (int i = 0; i < (); ++i) { ss << v[i]; if (i != () - 1) { ss << ", "; } } ss << "]"; cout << () << endl; return 0; }
The array can also be traversed directly, or the array can be converted to vector and then traversed:
int arr[] = {1, 2, 3, 4, 5}; std::vector<int> vec(std::begin(arr), std::end(arr));
Traversal of two-dimensional containers
#include <vector> #include <string> #include <sstream> #include <iostream> using namespace std; int main() { vector<vector<int>> vec2d = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; stringstream ss; ss << "["; for (int i = 0; i < (); ++i) { ss << "["; for (int j = 0; j < vec2d[i].size(); ++j) { ss << vec2d[i][j] << ", "; } (-2, ios_base::end); //Save the judgment: j==vec2d[i].size()-1 ss << "], "; } (-2, ios_base::end); //Save the judgment: i==()-1 ss << "]"; cout << () << endl; return 0; }
Use copy() to save the for loop:
#include <iostream> #include <algorithm> #include <vector> #include <iterator> #include <sstream> using namespace std; int main() { vector<int> vec1d = {1, 2, 3, 4, 5}; copy((), (), ostream_iterator<int>(cout, " ")); cout << endl; stringstream ss; ss << "["; copy((), (), ostream_iterator<int>(ss, ",")); (-1, ios_base::end); ss << "]"; cout << () << endl; return 0; }
All are written as conversion functions:
#include <iostream> #include <algorithm> #include <vector> #include <iterator> #include <sstream> using namespace std; string VectorToString(vector<int> vec, string sep = ",") { stringstream ss; ss << "["; copy((), (), ostream_iterator<int>(ss, sep.c_str())); (-(int)(), ios_base::end); ss << "]"; return (); } string Vector2dToString(vector<vector<int>> vec2d, string sep = ",") { stringstream ss; ss << "["; for (int i = 0; i < (); ++i) { ss << "["; copy(vec2d[i].begin(), vec2d[i].end(), ostream_iterator<int>(ss, sep.c_str())); (-(int)(), ios_base::end); ss << "]" << sep; } (-(int)(), ios_base::end); ss << "]"; return (); } int main() { vector<int> vec1d = {1, 2, 3, 4, 5}; vector<vector<int>> vec2d = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; cout << VectorToString(vec1d) << endl; cout << Vector2dToString(vec2d) << endl; cout << VectorToString(vec1d, ", ") << endl; cout << Vector2dToString(vec2d, ", ") << endl; return 0; }
Output:
[1,2,3,4,5]
[[1,2,3],[4,5,6],[7,8,9]]
[1, 2, 3, 4, 5]
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Brief summary
This article mainly introduces the method of converting arrays/containers into strings in common programming languages such as Python, Golang, Java, and C++.
In Python, you can traverse an array or list through a for loop or a list comprehension and convert it into a string through the join() method.
In Golang, you can use the for loop or range keyword and slice operator to traverse one-dimensional and two-dimensional arrays and convert them into strings through the Sprintf() function in the fmt package.
In Java, you can use a foreach loop to traverse one-dimensional and two-dimensional arrays, and use the () function to convert one-dimensional arrays into strings, and use the () function to convert two-dimensional arrays into strings.
In C++, you can use a variety of methods such as for loops, iterators, and range loops to traverse one-dimensional and two-dimensional containers, and convert the container into a string through the std::to_string() function and the std::stringstream class.
Summarize
This is the article about converting strings into Golang and other languages. For more information about converting strings to Golang arrays, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!