跳转到内容

Gambas/字符串操作

来自维基教科书,自由的教科书,共建更美好的世界

字符串连接

[编辑 | 编辑源代码]

连接运算符用一个&符号表示,用于将两个字符串连接在一起

 DIM bestclub AS String
 bestclub = "Liverpool" & " Football Club"    ' Liverpool Football Club

加号运算符不能用于连接字符串

[编辑 | 编辑源代码]

在Gambas中,与传统的BASIC不同,加号符号不能用作连接运算符。如果尝试将加号符号用于此目的,在尝试运行程序时将发生类型不匹配错误。

 ' This does not work in gambas
 PRINT "I have 3 cats" + " and 2 dogs"    ' You cannot concatenate strings by using a plus symbol

连接组合赋值运算符

[编辑 | 编辑源代码]

连接组合赋值运算符用一个&等号符号表示,也可以用于连接字符串

 DIM breakfast AS String
 breakfast = "bacon"
 breakfast &= " and eggs"    ' breakfast = breakfast & " and eggs" (using the andequals symbol)

搜索和替换

[编辑 | 编辑源代码]

我尝试在文本文件中搜索 - 两个函数:1- 按行和列搜索 2- 按位置搜索

- 第一个函数返回一个包含结果的数组,例如 ["1,12" , "2,1"],第一个元素是行,第二个是列

- 第二个函数也返回一个数组,但只有一个元素,例如:[1,2,45,455],每个元素是字符串位置


这里就是了!

AUTHOR: abom
MAIL: abom@linuxac.org

----

STATIC PUBLIC SUB searchfile(filename AS String, strser AS String) AS String[] 
  
  DIM icounter AS Integer, fn AS stream, ln AS String, wpos AS Integer, rstr AS NEW String[]
  DIM spos AS Integer
  icounter = 0
  
  IF Exist(filename) THEN 

     fn = OPEN filename FOR READ
     
      WHILE NOT Eof(fn) 
      
        LINE INPUT #fn, ln
        icounter = icounter + 1
          IF strser = "" THEN RETURN 
          spos = 0
          wpos = 0
          DO
           wpos = InStr(ln, strser, spos, gb.Text) 
          
          IF wpos <> 0 THEN 
             spos = wpos + Len(strser)
             rstr.add(icounter & "," & wpos) 
          END IF
          LOOP UNTIL (wpos = 0) 
      WEND

  END IF
  RETURN rstr 
  
END
----
STATIC PUBLIC SUB searchfilebypos(filename AS String, strser AS String) AS String[]
  
  DIM icounter AS Integer, fn AS stream, txt AS String, wpos AS Integer, rstr AS NEW String[]
  DIM spos AS Integer
  icounter = 0
  
  IF Exist(filename) THEN 
       wpos = 0 
       spos = 0
       
       txt = file.Load(filename)
       
       IF strser = "" THEN RETURN 
       DO  
        
           wpos = InStr(txt, strser, spos, gb.Text) 
  
          IF wpos <> 0 THEN 
             spos = wpos + Len(strser)  
             rstr.add(wpos) 
          END IF
          
       LOOP UNTIL (wpos = 0)
  END IF
  RETURN rstr 
  
END
华夏公益教科书