У меня есть два типа струнногоРазделить строку с Явой
command1|Destination-IP|DestinationPort
Command2|Destination-IP|DestinationPort|SourceIP|SourcePort|message
Я попытался разбить строку, чтобы получить переменные я начал программировать, как это, но не уверен, что это лучший способ
public String dstIp="";
public String dstPort="";
public String srcIp="";
public String scrPort="";
public String message="";
public String command="";
int first = sentence.indexOf ("|");
if (first > 0)
{
int second = sentence.indexOf("|", first + 1);
int third = sentence.indexOf("|", second + 1);
command = sentence.substring(0,first);
dstIp= sentence.substring(first+1,second);
dstPort= sentence.substring(second+1,third);
Должен ли я продолжать так? Или, может быть, использовать регулярное выражение? И если строка
command1|Destination-IP|DestinationPort
Я получаю сообщение об ошибке, потому что есть нет третьего |
'myStr.split (" \\ | ");' Или 'myStr.split (Pattern.quote (" | "));'. – Maroun
Вы также можете использовать один из [StringUtils.split] (http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#split (java.lang. String)) из apache commons, например 'StringUtils.split (предложение, '|')' –