我有一个根据分隔符"
(双引号)搜索的字符串。
因此,当我输入字符串“program”
时,它能够根据分隔符搜索字符串的开头和结尾,并返回我放入 vector 中的字符串program。
现在,如果我输入字符串 "program"123""
,它会返回 program
、123
、123"
等子字符串。
现在我想要的结果是 program"123"
,根据用例,它是一个有效的字符串,但它包含 "
作为字符串的一部分,这就是按分隔符搜索无法区分字符串开头和结尾的地方。
有人可以帮忙解释一下逻辑吗?
以下是我正在使用的方法。
enter code here
公共(public)静态PVector tokenizeInput(最终字符串sCmd) 抛出异常OpenQuotedString { if (sCmd == null) { 返回空值; }
PVector rc = new PVector();
if (sCmd.length() == 0)
{
rc.add(StringTable.STRING_EMPTY);
return rc;
}
char chCurrent = '\0';
boolean bInWhitespace = true;
boolean bInQuotedToken = false;
boolean bDelim;
int start = 0;
int nLength = sCmd.length();
for (int i = 0; i < nLength; i++)
{
chCurrent = sCmd.charAt(i); // "abcd "ef"" rtns abdc ef ef"
bDelim = -1 != APIParseConstants.CMD_LINE_DELIMS.indexOf(chCurrent);
if (bInWhitespace) // true
{
// In whitespace
if (bDelim)
{
if ('\"' == chCurrent)
{
start = i + 1;
bInQuotedToken = true;
bInWhitespace = false;
} // if ('\"' == chCurrent)
}
else
{
start = i;
bInWhitespace = false;
} // else - if (bDelim)
}
else
{
// Not in whitespace
boolean bAtEnd = i + 1 == nLength;
if (!bDelim)
{
continue;
}
else
{
if ('\"' == chCurrent)
{
if (!bInQuotedToken)
{
// ending current token due to '"'
if (bAtEnd)
{
// non terminated quoted string at end...
throw new ExceptionOpenQuotedString(
sCmd.substring(start));
}
else
{
rc.add(sCmd.substring(start, i)); // include quote
bInQuotedToken = true;
bInWhitespace = false;
} // if (bAtEnd)
}
else
{
// ending quoted string
//if (!bAtEnd)
{
rc.add(sCmd.substring(start, i)); // don't include quote
bInQuotedToken = false;
bInWhitespace = true;
} // if (bAtEnd)
} // else - if (!bInQuotedToken)
}
else
{
// got delim (not '"')
if (!bAtEnd && !bInQuotedToken)
{
rc.add(sCmd.substring(start, i));
bInWhitespace = true;
} // if (bAtEnd)
} // else - if ('\"' == chCurrent)
} // else - if (!bDelim)
} // else - if (bInWhitespace)
} // for (short i = 0; i < nLength; i++)
if (!bInWhitespace && start < nLength)
{
if (!bInQuotedToken || chCurrent == '"')
{
rc.add(sCmd.substring(start));
}
else
{
throw new ExceptionOpenQuotedString(sCmd.substring(start));
} // else - if (!bInQuotedToken)
} // if (!bInWhitespace && start < nLength)
return rc;
}
最佳答案
你应该逃避内部“。 否则,您可以检查第一个和最后一个 "字符的位置,并使用这些位置作为分隔符来分割/剪切字符串。
关于java - 工作场所与字符串相关的编程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11205791/