【问题标题】:String manipulation in adaada中的字符串操作
【发布时间】:2015-05-06 13:29:16
【问题描述】:

我正在获取字符串中的目录路径,例如"C:\Users\Me\Desktop\Hello”,我正在尝试获取最后一个目录,但没有成功。

我尝试了很多对字符串的操作,但最终我还是一无所获……我会很感激能得到一些帮助。谢谢!

这是我的第一个想法:

Get_Line(Line, Len);
while (Line /="") loop
   FirstWord:=Index(Line(1..Len),"\")+1;
   declare
      NewLine :String := (Line(FirstWord .. Len));
   begin
      Line:=NewLine ; 
   end;
end loop;

我知道它不起作用(我无法将 NewLine 分配给 Line,因为它们的长度不匹配),现在我被卡住了。

【问题讨论】:

    标签: string ada


    【解决方案1】:

    我假设您想要操作目录(和文件)名称,而不仅仅是任何旧字符串?

    在这种情况下,您应该查看标准库包 Ada.Directories (ARM A.16) 和 Ada.Directories.Hierarchical_File_Names (ARM A.16.1):

    with Ada.Directories;
    with Ada.Text_IO; use Ada.Text_IO;
    procedure Tal is
       Line : constant String := "C:\Users\Me\Desktop\Hello";
    begin
       Put_Line ("Full_Name: "
                   & Ada.Directories.Full_Name (Line));
       Put_Line ("Simple_Name: "
                   & Ada.Directories.Simple_Name (Line));
       Put_Line ("Containing_Directory: "
                   & Ada.Directories.Containing_Directory (Line));
       Put_Line ("Base_Name: "
                   & Ada.Directories.Base_Name (Line));
    end Tal;
    

    另一方面,如果你想进行简单的字符串操作,你可以使用类似

    with Ada.Strings.Fixed;
    with Ada.Text_IO; use Ada.Text_IO;
    procedure Tal is
    
       function Get_Last_Word (From : String;
                               With_Separator : String)
                              return String is
          Separator_Position : constant Natural :=
            Ada.Strings.Fixed.Index (Source => From,
                                     Pattern => With_Separator,
                                     Going => Ada.Strings.Backward);
       begin
          --  This will fail if there are no separators in From
          return From (Separator_Position + 1 .. From'Last);   --'
       end Get_Last_Word;
    
       Line : constant String := "C:\Users\Me\Desktop\Hello";
    
       Last_Name : constant String := Get_Last_Word (Line, "\");
    
    begin
       Put_Line (Last_Name);
    end Tal;
    

    如您所见,将逻辑放入Get_Last_Word 允许您将Last_Namedeclare 块中提升出来。但是永远不可能用它自己的子字符串覆盖一个固定的字符串(除非你准备好处理尾随空格,也就是说):最好不要尝试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多