c# - 奇怪的字符串换行的东西
问题描述
我目前正在尝试纠正 C# 中的 Lexer(可能很愚蠢,但这只是编程实践,它是我最了解的语言),我遇到了一个奇怪的问题。我已将一个单独的文件拆分为令牌并将其显示到控制台中。但是,每次我运行我的程序时,我都会比脚本中的标记多一行。我已经尝试了将近一天来让它工作,但它不会。这是我的代码和控制台本身:
public class Lexer
{
public static List<List<Lexer_Token>> GetTokens(string filePath)
{
List<List<Lexer_Token>> tokens = new List<List<Lexer_Token>>();
string[] commands = GetCommands(Reader.ReadFile(filePath));
for (int c = 0; c < commands.Length; c++)
{
List<Lexer_Token> currentTokens = StoreAsTokens(commands[c]);
tokens.Add(currentTokens);
}
return tokens;
}
private static List<Lexer_Token> StoreAsTokens(string command)
{
List<Lexer_Token> tokenList = new List<Lexer_Token>();
string[] tokens = SplitUpCommand(command, ' ');
for (int t = 0; t < tokens.Length; t++)
{
string currentToken = tokens[t];
Lexer_Token token = new Lexer_Token();
token.symbol = currentToken;
tokenList.Add(token);
}
return tokenList;
}
private static string[] SplitUpCommand(string command, char character)
{
return command.Split(character);
}
private static string[] GetCommands(string contents)
{
return contents.Split(';');
}
public static string FormatTokens(List<List<Lexer_Token>> list)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.Count; i++)
{
List<Lexer_Token> currentTokenList = list[i];
for (int j = 0; j < currentTokenList.Count; j++)
{
Lexer_Token currentToken = currentTokenList[j];
sb.Append("ID: " + currentToken.id.ToString());
sb.Append(" Type: " + currentToken.type);
sb.Append(" Line: " + currentToken.lineNumber.ToString()
+ "[" + currentToken.startingCharacterIndex.ToString() + "]");
sb.Append(" Symbol: " + currentToken.symbol);
if (i != list.Count - 1)
{
sb.Append("\n");
}
}
}
return sb.ToString();
}
}
public class Lexer_Token
{
public int id;
public int lineNumber;
public int startingCharacterIndex;
public string type;
public string symbol;
}
解决方案
如果您不关心分配,您可以使用 Join 和 linq 执行此操作,也许更容易阅读
static string Output(Lexer_Token currentToken)
{
var sb = new StringBuilder();
sb.Append($"ID: {currentToken.id}");
sb.Append($" Type: {currentToken.type}");
sb.Append($" Line: {currentToken.lineNumber}[{currentToken.startingCharacterIndex}]");
sb.Append($" Symbol: {currentToken.symbol}");
return sb.ToString();
}
public static string FormatTokens(List<List<Lexer_Token>> list)
{
var lines = list.SelectMany(currentTokenList => currentTokenList).Select(Output);
return string.Join(Environment.NewLine, lines);
}
推荐阅读
- javascript - 提交时形成ajax组标签和值
- wpf - 具有自动行数的wpf网格
- javascript - 与在 useEffect 中分配转发的 ref 相比,useImperativeHandle 有什么好处?
- c# - 图像和 Html Head 组件的 Blazor 加载问题
- android - 获取 Google 照片列表返回 401 未经身份验证
- r - 如何将滑块输入与选择输入相乘,其中结果显示为文本输出
- r - 我们如何使用 read_excel 在 R 中读取 .xlsx 文件?
- c++ - 发送一个 c++ std::vector
通过 mpi - python - Python 3:如何转换
至 - java - 在我自己的项目中使用 jrawio 会导致错误