Самый надежный символ разделения

Экспресс Visual C++ является прекрасным и свободным IDE для Windows, который идет с компилятором.

, Если Вы более довольны решениями для командной строки в целом и gcc, в частности, MinGW или , Cygwin мог бы быть больше Вами переулок. Они также оба свободны.

48
задан JL. 10 December 2009 в 00:17
поделиться

11 ответов

We currently use

public const char Separator = ((char)007);

I think this is the beep sound, if i am not mistaken.

53
ответ дан 7 November 2019 в 12:15
поделиться

Aside from 0x0, which may not be available (because of null-terminated strings, for example), the ASCII control characters between 0x1 and 0x1f are good candidates. The ASCII characters 0x1c-0x1f are even designed for such a thing and have the names File Separator, Group Separator, Record Separator, Unit Separator. However, they are forbidden in transport formats such as XML.

In that case, the characters from the unicode private use code points may be used.

One last option would be to use an escaping strategy, so that the separation character can be entered somehow anyway. However, this complicates the task quite a lot and you cannot use String.Split anymore.

20
ответ дан 7 November 2019 в 12:15
поделиться

Я обычно предпочитаю символ « | » в качестве символа разделения. Если вы не уверены, какой пользователь вводит текст, вы можете запретить пользователю вводить некоторые специальные символы, и вы можете выбрать один из этих символов, разделенный символ.

8
ответ дан 7 November 2019 в 12:15
поделиться

It depends what you're splitting.

In most cases it's best to use split chars that are fairly commonly used, for instance

value, value, value

value|value|value

key=value;key=value;

key:value;key:value;

You can use quoted identifiers nicely with commas:

"value", "value", "value with , inside", "value"

I tend to use , first, then |, then if I can't use either of them I use the section-break char §

Note that you can type any ASCII char with ALT+number (on the numeric keypad only), so § is ALT+21

6
ответ дан 7 November 2019 в 12:15
поделиться

\0 is a good split character. It's pretty hard (impossible?) to enter from keyboard and it makes logical sense.

\n is another good candidate in some contexts.

And of course, .Net strings are unicode, no need to limit yourself with the first 255. You can always use a rare Mongolian letter or some reserved or unused Unicode symbol.

6
ответ дан 7 November 2019 в 12:15
поделиться

Есть перегрузок String.Split, которые принимают разделители строк ...

4
ответ дан 7 November 2019 в 12:15
поделиться

I'd personally say that it depends on the situation entirely; if you're writing a simple TCP/IP chat system, you obviously shouldn't use '\n' as the split.. But '\0' is a good character to use due to the fact that the users can't ever use it!

2
ответ дан 7 November 2019 в 12:15
поделиться

First of all, in C# (or .NET), you can use more than one split characters in one split operation.

String.Split Method (Char[]) Reference here
An array of Unicode characters that delimit the substrings in this instance, an empty array that contains no delimiters, or null reference (Nothing in Visual Basic).

In my opinion, there's no MOST reliable split character, however some are more suitable than others.

Popular split characters like tab, comma, pipe are good for viewing the un-splitted string/line.

If it's only for storing/processing, the safer characters are probably those that are seldom used or those not easily entered from the keyboard.

It also depend on the usage context. E.g. If you are expecting the data to contain email addresses, "@" is a no no.

Say we were to pick one from the ASCII set. There are quite a number to choose from. E.g. " ` ", " ^ " and some of the non-printable characters. Do beware of some characters though, not all are suitable. E.g. 0x00 might have adverse effect on some system.

2
ответ дан 7 November 2019 в 12:15
поделиться

Это во многом зависит от контекста, в котором он используется. Если вы говорите об очень общем ограничивающем символе, то я не думаю, что существует универсальный ответ.

Я считаю, что нулевой символ ASCII '\ 0' часто является хорошим кандидатом, или вы можете пойти с идеей Ницмахоны и использовать более одного символа, тогда это может быть настолько безумным, насколько вы хотите.

В качестве альтернативы вы можете проанализировать ввод и избежать любых экземпляров вашего ограничивающего символа.

1
ответ дан 7 November 2019 в 12:15
поделиться

"|" pipe sign is mostly used when you are passing arguments.. to the method accepting just a string type parameter. This is widely used used in SQL Server SPs as well , where you need to pass an array as the parameter. Well mostly it depends upon the situation where you need it.

0
ответ дан 7 November 2019 в 12:15
поделиться

You can safely use whatever character you like as delimiter, if you escape the string so that you know that it doesn't contain that character.

Let's for example choose the character 'a' as delimiter. (I intentionally picked a usual character to show that any character can be used.)

Use the character 'b' as escape code. We replace any occurrence of 'a' with 'b1' and any occurrence of 'b' with 'b2':

private static string Escape(string s) {
   return s.Replace("b", "b2").Replace("a", "b1");
}

Now, the string doesn't contain any 'a' characters, so you can put several of those strings together:

string msg = Escape("banana") + "a" + Escape("aardvark") + "a" + Escape("bark");

The string now looks like this:

b2b1nb1nb1ab1b1rdvb1rkab2b1rk

Now you can split the string on 'a' and get the individual parts:

b2b1nb1nb1
b1b1rdvb1rk
b2b1rk

To decode the parts you do the replacement backwards:

private static string Unescape(string s) {
   return s.Replace("b1", "a").Replace("b2", "b");
}

So splitting the string and unencoding the parts is done like this:

string[] parts = msg.split('a');
for (int i = 0; i < parts.length; i++) {
  parts[i] = Unescape(parts[i]);
}

Or using LINQ:

string[] parts = msg.Split('a').Select<string,string>(Unescape).ToArray();

If you choose a less common character as delimiter, there are of course fewer occurrences that will be escaped. The point is that the method makes sure that the character is safe to use as delimiter without making any assumptions about what characters exists in the data that you want to put in the string.

19
ответ дан 7 November 2019 в 12:15
поделиться
Другие вопросы по тегам:

Похожие вопросы: