如何转换char数组中的字符串? [英] How to transform a string in a char array?

查看:93
本文介绍了如何转换char数组中的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有一个像这样的字符串

Hi,

I have a string like this

\x00\x00\x00\x00\x00\x00\x00\x00

我想在char数组中更改它,例如:00 00 00 00 00 00 00 00;



我怎么能这样做?



谢谢。



我是什么尝试过:



我已经尝试过拆分功能,但它没有用。

也许我没有正确使用它。

and I want to change it in a char array, like this : 00 00 00 00 00 00 00 00;

How can I made it like that?

Thanks.

What I have tried:

I have already tried the split function but it didn't worked.
Maybe I didn't use it right.

推荐答案

你的意思是

Do you mean
string s = @"\x00\x00\x00\x00\x00\x00\x00\x00";
string[] a = s.Split(new string []{@"\x"},StringSplitOptions.RemoveEmptyEntries);
char[] ca = new char[a.Length];
for (int k = 0; k < a.Length; ++k)
  ca[k] = System.Convert.ToChar(System.Convert.ToUInt32(a[k], 16));


这是一个指定十六进制的C源文件字符串字符的代码。



如果你真的有这样的字符串(即字符代码0x5C 0x78 0x30 0x30)你可以从字符串中删除\ x并将结果字符串转换为字节数组。这可以转换为char数组(但可能没有必要取决于你想用它做什么)。



删除\ x 你可以使用

That is a C source file string specifying hex codes for the characters.

If you really have such a string (that is character codes 0x5C 0x78 0x30 0x30) you can remove the "\x" from the string and convert the resulting string to a byte array. That can be than converted to a char array (but it might not be necessary depending on what you want to do with it).

To remove the "\x" you can use
String.Replace(@"\x", "");

String.Replace("\\x", "");



有很多例子可以将结果字符串转换为字节数组。只需在网上搜索c#十六进制字符串到字节数组之类的内容:

c# - 如何将十六进制字符串转换为字节数组? - 堆栈溢出 [ ^ ]


这将取决于你的字符串是什么 - 并且有两种可能性

这是一个:

That's going to depend on what your string is exactly - and there are two possibilities
Here's one:
string inp = @"\x00\x00\x00\x00\x00\x00\x00\x00";



这是另一个:


And here's the other:

string inp = "\x00\x00\x00\x00\x00\x00\x00\x00";



你需要如何处理它们是不同的。

第一个是相当微不足道的:


How you need to handle them is different.
The first is fairly trivial:

string inp = @"\x00\x00\x00\x00\x00\x00\x00\x00";
string[] values = inp.Split(new string[] { "\\x" }, StringSplitOptions.RemoveEmptyEntries);
char[] data = new char[values.Length];
int i = 0;
foreach (string s in values)
    {
    data[i++] = (char)Convert.ToByte(s, 16);
    }

第二个更简单:一个字符串是一个char数组,实际上你可以通过索引访问单个字符,但是:

The second is even more trivial: a string is a char array, effectively in that you can access individual characters via an index, but:

string inp = "\x00\x00\x00\x00\x00\x00\x00\x00";
char[] data = inp.ToArray();


这篇关于如何转换char数组中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆