【发布时间】:2017-08-14 13:09:39
【问题描述】:
我正在生成一个文件,格式如下:
=
有时第二个字符串是空的,所以我必须根据第一个字符串生成一个值。例如,如果第一个字符串是“StackOverflow”,我将生成第二个值作为“Stack Overflow”。
问题是有时第一个值会有一个竖线字符(旧平台的残余),即“18|2”。我不想在管道符号之前或之后添加空格。我有一个循环来检查第一个字符串值中的每个字符(来自上面的格式)。我想检查前一个字符是否是管道,并忽略这种情况。问题是,我不确定如何检查管道“|”字符。
编辑这是现在的代码:
private string createNewTitleFromFieldId(string fieldId) {
if (string.IsNullOrWhiteSpace(fieldId))
throw new ArgumentNullException();
string newTitleValue = "";
for (int i = 0; i < fieldId.Length; i++) {
char currentChar = fieldId[i];
char previousChar = i == 0 ? fieldId[i] : fieldId[i - 1];
// Only perform checks if the current character is not the first character in the string.
if (i != 0) {
// If the current character is upper-case, and preceded by a lower-case character, append a preceding space.
if (char.IsUpper(currentChar) && !char.IsUpper(previousChar))
newTitleValue += string.Format(" {0}", currentChar);
// If the current character is a number, but is not preceded by a number.
else if (char.IsNumber(currentChar) && !char.IsNumber(previousChar))
newTitleValue += string.Format(" {0}", currentChar);
// If the character is a number, but preceded by a pipe "|" character.
else if (char.IsNumber(currentChar) && char.Equals(previousChar, '|'))
newTitleValue += currentChar;
// Add the current character to the Title if it does not match the above criteria.
else newTitleValue += currentChar;
}
// Add the current character if the index is 0, otherwise we lose the first character.
else newTitleValue += currentChar;
}
return newTitleValue;
}
所需输入/输出示例:
输入:“StackOverFlow”输出:“堆栈溢出”
in: "Stack1Over11Flow111" out: "Stack 1 Over 11 Flow 111"
输入:“Stack|1OverFlow|11”输出:“Stack|1 Over Flow|11”
【问题讨论】:
-
由于您没有提供如何将
"StackOverflow"转换为“Stack Overflow"”的代码,因此很难猜测如何通过忽略管道来做到这一点。期望的结果是什么"Stack|Overflow"? -
很抱歉。如果小写字母后面有一个大写字母,或者前面没有另一个数字,我只是在第一个字符串中添加空格。输入/输出示例为: in: "18|2" out: "18|2" in: "StackOverFlow" out: "Stack Over Flow" in: "Stack1OverFlow22" out "Stack 1 Over Flow 22" 我有除了第一个带有管道字符的示例外,一切正常。我的代码在管道字符后添加了一个空格。
-
很难看出为什么您的代码无法正常工作,因为您没有将其全部包含在内。如果您正在检查大写字符和数字,则无需检查管道。
-
我已经用我的完整代码更新了原始帖子。