跳轉到內容

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
華夏公益教科書