Compare text lines! =D

Share your advanced PureBasic knowledge/code with the community.
josku_x
Addict
Addict
Posts: 997
Joined: Sat Sep 24, 2005 2:08 pm

Compare text lines! =D

Post by josku_x »

Code updated for 5.20+

Hello!

I used this technique very much. It stores text lines into an array and then compares each array's values to tell if the value was changed or not. This is pretty useful for INI file processing etc... Feel free to modify it.

Hope you like it:

Code: Select all

First$="Finland"+#CRLF$+"Sweden"+#CRLF$+"France"+#CRLF$+"Somewhere"
Second$="Finland"+#CRLF$+"Sweden!!!"+#CRLF$+"France???"+#CRLF$+"Monaco"+#CRLF$+"Somewhere?"

Procedure CompareTextLines(First$, Second$, NewLineFormat$)
  ; Do initialization and store each string's lines.
  Select UCase(NewLineFormat$)
    Case "CRLF"
      NLF$=#CRLF$
    Case "LF"
      NLF$=#LF$
    Case "CR"
      NLF$=#CR$
    Default
      NLF$=#CRLF$
  EndSelect
  Global FirstLineCount, SecondLineCount
  FirstLineCount=CountString(First$, NLF$)+1
  SecondLineCount=CountString(Second$, NLF$)+1
  If FirstLineCount<SecondLineCount
    BigLineCount=SecondLineCount
  ElseIf FirstLineCount>SecondLineCount
    BigLineCount=FirstLineCount
  ElseIf FirstLineCount=SecondLineCount
    BigLineCount=FirstLineCount
  EndIf
  Dim FirstLines.s(BigLineCount)
  Dim SecondLines.s(BigLineCount)
  For LinePos=1 To FirstLineCount
    FirstLines(LinePos)=StringField(First$, LinePos, NLF$)
  Next
  For LinePos=1 To SecondLineCount
    SecondLines(LinePos)=StringField(Second$, LinePos, NLF$)
  Next
  ; Now compare each lines values on both text's.
  For LinePos=1 To BigLineCount
    Debug "Line "+Str(LinePos)+":"
    If FirstLines(LinePos)<>SecondLines(LinePos)
      Debug "Before: "+Chr(34)+FirstLines(LinePos)+Chr(34)
      Debug "After: "+Chr(34)+SecondLines(LinePos)+Chr(34)
    ElseIf FirstLines(LinePos)=SecondLines(LinePos)
      Debug "Same value: "+Chr(34)+FirstLines(LinePos)+Chr(34)
    EndIf
  Next
EndProcedure

CompareTextLines(First$, Second$, "CRLF")
It should work on all platforms, as only pure PB code was used.
Usage:
CompareTextLines(First$, Second$, NewLineFormat$)
The First$ parameter is the "original" text, while the Second$ parameter is used for the "new version" of the text. The NewLineFormat$ parameter is indicated to tell what kind of newline should the code use. This can be either "CRLF" (Windows) or "LF" (Linux) or "CR" (MacOSX).
Have fun :D