[英]How to Divide a String Into char Arrays
I am trying to divide a string into char arrays. 我正在尝试将字符串分成char数组。 I have a program that converts a char array (of 7 chars) from binary to ASCII text. 我有一个程序可以将char数组(共7个字符)从二进制转换为ASCII文本。 So what I am trying to do is break a string up into char arrays of 7 chars in 'Arduino code' or in C, C++ or Java. 所以我想做的是在“ Arduino代码”或C,C ++或Java中将字符串分成7个字符的字符数组。 Any suggestions? 有什么建议么? Thanks! 谢谢!
Edit: 编辑:
Here is the program that I am using: 这是我正在使用的程序:
String getText(String str) {
String text = "";
char bits[] = "1001000";
char new_char = 0;
for (int i = 7; i >= 0; i--)
{
int current_bit = bits[i] - '0';
new_char |= current_bit << (7-i);
}
text += (String) new_char + "";
return text;
}
You can use: 您可以使用:
String s = "java";
char[] ch = s.toCharArray();
UPDATE 更新
Well, I am watching this post after I saw a red (-2) point in my reputation list. 好吧,当我在信誉列表中看到红色(-2)点后,我正在看这篇文章。 And to my surprise the question is different from what it had been posted for Which I had answered. 令我惊讶的是,这个问题与我为之回答的问题有所不同。 Now after reading your Edited question I am posting the new answer . 现在,在阅读您的“已编辑问题”后,我将发布新答案 。 You can use Integer.parseInt()
method to achieve what you are looking for in Java . 您可以使用Integer.parseInt()
方法来实现Java所需的功能 。 Here is the short demo of how this method could be used: 这是如何使用此方法的简短演示:
class BinaryToWords
{
static String returnString(String input)
{
String parts[] = input.split("\\s+");
StringBuilder sBuilder = new StringBuilder();
for (String part : parts)
{
int i = Integer.parseInt(part, 2);//Parses the string argument(part) as a signed integer in the radix(2).
char ch = (char)i;
sBuilder.append(String.valueOf(ch));
}
return sBuilder.toString();
}
public static void main(String[] args)
{
String binary = "1001000 1100101 1101100 1101100 1101111 100000 1010111 1101111 1110010 1101100 1100100";//Input the binary format.
System.out.println(returnString(binary));
}
}
The output for the above code is: 上面代码的输出是:
Hello World
You can check this for other inputs too..And let me know if it working fine for all acceptable inputs. 您也可以检查其他输入。.让我知道它对于所有可接受的输入是否都能正常工作。
What do you mean? 你什么意思? AC\\C++ string is essentially an array of character.. If you have a pointer to a char (=string) then there's your array. AC \\ C ++字符串本质上是一个字符数组。.如果您有一个指向char(= string)的指针,那么这里就有您的数组。 Otherwise if you have an std::string, you can use its .c_str() method. 否则,如果您有std :: string,则可以使用其.c_str()方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.