Having problems coding a char array to a string
I'm trying to use a string constructor to convert the 2d char array into a string. Having problems finding the proper constructor. I attempted using various constructors but 开发者_Python百科nothing seems to work.
char chars[][]= {{'a', 'b', 'c'}, {'d', 'e', 'f'}};
StringBuilder sb = new StringBuilder();
for(int i = 0; i<2 ;i++){
for(int j =0; j<3; j++){
sb.append(chars[i][j]);
}
}
System.out.print(sb.toString());
this is one of my option to do .. nevertheless.. there might be a good code!! look for it!!!
This will give you a list of String's
char[][] arr={{'a', 'b', 'c'}, {'d', 'e', 'f'}};
List<String> list=new ArrayList<String>();
for(char[] ar:arr)
{
list.add(new String(ar));
}
If you want the 2d char array as a single string:
StringBuilder b=new StringBuilder();//use string builder instead of list
for(char[] ar:arr)
{
b.append(new String(ar));
}
If you simply want to print the char 2d array:
Arrays.deepToString(arr));
What do you mean a 2d char array into a string?
If you have this: {{'a', 'b', 'c'}, {'d', 'e', 'f'}}
Do you want the result to be: "abcdef"?
You want to turn a 2d char array into a single string? Seems kind of strange. Do you want to just concatenate each row at the end of the last row?
Long story short, I don't think you will find a built in constructor to do that. You are probably going to have to write something to do that conversion on your own.
EDIT:
Based on your comments it looks like you are using the wrong data structure when you originally read the file. Here is a code snippet to read an entire file into a string so you don't have to do any conversion later.
StreamReader MyStreamReader = new StreamReader(@"c:\Projects\Testing.txt");
string fileContents= MyStreamReader.ReadToEnd();
MyStreamReader.Close();
精彩评论