在 VHDL 中修改字符串的最佳方法

Best way to modify strings in VHDL

我目前正在为自己制作的 VHDL 设计编写测试台,我需要将消息写入文本文件。消息的格式为

[instance_name];[simulation_time] 

(即 U0;700 ns)且文件名必须为 [instance_name].log。获取实例名称和模拟时间没问题,但写入自定义文件名一直有问题。在模拟下,实例名称将以格式给出:

"U0\ComponentX\test\" 

我想用下划线替换斜杠。有没有简单的方法可以做到这一点?

我们的 PoC Library has quite a big collection on string operations/functions. There is a str_replace function in PoC.strings that should solve your question. There is also the PoC.utils 包具有非字符串相关的功能,这也有助于处理字符串和文件 I/O。

一个简单的实现:

function replace(str : STRING) return STRING
  variable Result : STRING(str'range) := str;
begin
  for i in str'range loop
    if (Result(i) = '\') then
      Result(i)  := '_';
    end if;
  loop;
  return Result;
end function;

用法:

constant original : STRING := "U0\ComponentX\test\";
constant replaced : STRING := replace(original);

简单的替换字符函数,它更通用并且可以完成相同的工作(@Paebbels 的回答没有错)

      function fReplaceChar(
        a : character;
        x : character;
        s : string) return string
      is
        variable ret : string(s'range) := s;
      begin
        for i in ret'range loop
          if(ret(i) = a) then
            ret(i) := x;
          end if;
        end loop;
        return ret;
      end function fReplaceChar;

如果要替换的字符不止一个,可以叠加函数:

  function fReplaceChar(
    a : character;
    b : character;
    x : character;
    s : string) return string
  is
  begin
    return fReplaceChar(b, x, fReplaceChar(a, x, s));
  end function fReplaceChar;

或函数调用:

 fReplaceChar(')','_',fReplaceChar(':','(','_',tb'instance_name));

例如:

 process 
 begin
     report lf & tb'instance_name & lf &
     fReplaceChar(')','_',fReplaceChar(':','(','_',tb'instance_name));
     wait;
 end process;

给出:

# ** Note:
# :tb(sim):
# _tb_sim__