Replacing one character in a string by its index in Delphi? - string

I've tried the following code without success.
string.remove[index];
string.insert[index];
Can anyone suggest how can I correct this code?

Just do this:
stringVariable[index] := 'A';

You can directly access a string like it was a character array in Delphi:
MyString[Index] := NewChar;
For multiple character deletions and inserts, the System unit provides Delete and Insert:
System.Delete(MyString, Index, NumChars);
System.Insert(NewChars, MyString, Index);
Recent versions of Delphi provide the helper functions to string:
MyString := MyString.Remove(3, 1);
MyString := MyString.Insert(3, NewChars);
Once again, please read the tutorials I've referred you to twice previously. This is a very basic Pascal question that any of them would have answered for you.

Here is another way to do it. Have fun with Delphi
FUNCTION ReplaceCharInPos(CONST Text: String; Ch: Char; P: Integer): String;
VAR Lng: Integer; left, Right: String;
BEGIN
Lng:= Length(Text);
IF Lng = 0 THEN
Result:= ''
ELSE IF (P < 1) OR (P > Lng) THEN
Result:= Text
ELSE IF P = 1 THEN
Result:= Ch + Copy(Text, 2, Lng - 1)
ELSE IF P = Lng THEN
Result:= Copy(Text, 1, Lng - 1) + Ch
ELSE BEGIN
Left:= Copy(Text, 1, P - 1);
Right:= Copy(Text, P + 1, Lng - P);
Result:= Left + Ch + Right;
END;
END;

Related

Read strings from file and give option to choose installation

I want to make Steam backups installer. However, Steam allow to user make multiple library folders which makes installation difficult.
There are a few tasks that I want to perform.
Installer should identify path from registry to identify where Steam is installed.
The resulting path from registry open file
X:\Steam\config\config.vdf
and read value of "BaseInstallFolder_1", "BaseInstallFolder_2", "BaseInstallFolder_3" and etc.
Example of config.vdf:
"NoSavePersonalInfo" "0"
"MaxServerBrowserPingsPerMin" "0"
"DownloadThrottleKbps" "0"
"AllowDownloadsDuringGameplay" "0"
"StreamingThrottleEnabled" "1"
"AutoUpdateWindowStart" "-1"
"AutoUpdateWindowEnd" "-1"
"LastConfigstoreUploadTime" "1461497849"
"BaseInstallFolder_1" "E:\\Steam_GAMES"
The resulting path or paths of the file config.vdf bring in DirEdit
If user have multiple paths to the folder in different locations then give option select through DirTreeView or Radiobuttons.
How it should look like:
I know how to identify Steam path
WizardForm.DirEdit.Text := ExpandConstant('{reg:HKLM\SOFTWARE\Valve\Steam,InstallPath|{pf}\Steam}')+ '\steamapps\common\gamename';
But it is difficult to perform other tasks
Thanks in advance for your help.
To parse the config.vdf file:
Load the file using LoadStringsFromFile.
And use string functions like Copy, Pos, Delete, CompareText to parse it.
To keep the results use array of string (or predefined TArrayOfString). To allocate the array, use SetArrayLength.
The code may be like:
function ParseSteamConfig(FileName: string; var Paths: TArrayOfString): Boolean;
var
Lines: TArrayOfString;
I: Integer;
Line: string;
P: Integer;
Key: string;
Value: string;
Count: Integer;
begin
Result := LoadStringsFromFile(FileName, Lines);
Count := 0;
for I := 0 to GetArrayLength(Lines) - 1 do
begin
Line := Trim(Lines[I]);
if Copy(Line, 1, 1) = '"' then
begin
Delete(Line, 1, 1);
P := Pos('"', Line);
if P > 0 then
begin
Key := Trim(Copy(Line, 1, P - 1));
Delete(Line, 1, P);
Line := Trim(Line);
Log(Format('Found key "%s"', [Key]));
if (CompareText(
Copy(Key, 1, Length(BaseInstallFolderKeyPrefix)),
BaseInstallFolderKeyPrefix) = 0) and
(Line[1] = '"') then
begin
Log(Format('Found base install folder key "%s"', [Key]));
Delete(Line, 1, 1);
P := Pos('"', Line);
if P > 0 then
begin
Value := Trim(Copy(Line, 1, P - 1));
StringChange(Value, '\\', '\');
Log(Format('Found base install folder "%s"', [Value]));
Inc(Count);
SetArrayLength(Paths, Count);
Paths[Count - 1] := Value;
end;
end;
end;
end;
end;
end;

How can I get a char of a String in delphi 7?

This is something that should be easey but I just can´t get it work.
I come from java so maby I have a error in my thinking here.
What I want to do is that I have a string with two letters like 't4' or 'pq'.
Now I just want to get each of the chracters in the string as an own string.
So I do:
firstString := myString[0];
but I don´t even get this compiled.
So I figured that they start counting form 1 and put 1 as an index.
Now I do this in a while loop and the first time I go through it it works fine. Then the second time the results are just empty or wrong numbers.
What am I missing here?
(I also tried copy but that doesn´t work either!)
while i < 10 do
begin
te := 'te';
a := te[1];
b := te[2];
i := i +1;
end;
the first loop a is 't' and b is 'e' as I would expect. The second time a is '' and b ist 't' which I don´t understand!
Strings are 1-based, not zero-based. Try the following, after adding StrUtils to your Uses list (for DupeString):
var
MyString : String;
begin
MyString := '12345';
Caption := StringOfChar(MyString[1], 8) + ':' + DupeString(Copy(MyString, 3, 2), 4);
You could split it up to mke it easier to follow, of course:
var
MyString,
S1,
S2,
S3: String;
begin
MyString := '12345';
S1 := StringOfChar(MyString[1], 8);
S2 := Copy(MyString, 3, 2);
S3 := DupeString(S2, 4);
Caption := S1 + ':' + S3;

Delete text after specific character

I have the text inside TEdit box:
'955-986, total = 32'
How would I delete all text after the comma, so it will only left '955-986'
I tried to limit the TEdit Length, but it's not working as I wanted it to be.
What if there'd be no comma? full non-cut string or empty string ?
Below is your idea of limiting string length, but only applied if at least one comma was found.
var
tmpStr:string;
commaPosition:integer;
begin
tmpStr := Edit1.Text;
commaPosition := pos(',',tmpStr);
if commaPosition > 0 then begin
SetLength(tmpStr, commaPosition - 1);
Edit1.Text := tmpStr;
end;
end;
You could use this code:
var
tmpStr:string;
commaPosition:integer;
begin
tmpStr := Edit1.Text;
commaPosition := pos(',',tmpStr);
tmpStr := copy(tmpStr,1,commaPosition-1);
Edit1.Text := tmpStr;
end;
I'm not a Delphi-Programmer (any more). However, I guess you get the String from the Text-Property of your TEdit-Box object, search for the first occurrence of , and get the index thereof and replace the Text contained in your TEdit-Box by the substring from the beginning of the current string to the found index.
edit.Text := Copy(edit.Text, 1, Pos(',', edit.Text)-1);
Sources:
http://docwiki.embarcadero.com/Libraries/en/System.Copy
http://docwiki.embarcadero.com/Libraries/en/System.Pos
TEdit.Text is a property and cannot be passed as var parameter. But once you introduce temporary variable, you can delegate checking of character index returned from Pos to Delete and it will handle all of cases.
var
S: string;
begin
S := Edit1.Text; // try '955-986, total = 32' and '955-986; total = 32'
Delete(S, Pos(',', S), MaxInt);
Edit1.Text := S;
end;

How do I store and load a list of key-value pairs in a string?

I have a list of strings and the values they are to be replaced with. I'm trying to combine them in a list like 'O'='0',' .'='.', ... so it's easy for me to edit it and add more pairs of replacements to make.
Right now the best way I could think of it is:
var
ListaLimpeza : TStringList;
begin
ListaLimpeza := TStringList.Create;
ListaLimpeza.Delimiter := '|';
ListaLimpeza.QuoteChar := '"';
ListaLimpeza.DelimitedText := 'O=0 | " .=."';
ShowMessage('1o Valor = '+ListaLimpeza.Names[1]+' e 2o Valor = '+ListaLimpeza.ValueFromIndex[1]);
This works, but it's not good for visuals, since I can't code the before string (for ex ' .') like that (which is very visual for the SPACE character), only like (" .) so that the = works to assign a name and value in the TStringList.
The Names and Values by default have to be separated by =, in the style of Windows INI files. There's no way AFAICT to change that separator. As #SirRufo indicates in the comment (and which I had never noticed), you can change that using the TStringList.NameValueSeparator property.
This will give you an idea of what Delphi thinks is in your TStringList, which is not what you think it is:
procedure TForm1.FormCreate(Sender: TObject);
var
SL: TStringList;
Temp: string;
i: Integer;
begin
SL := TStringList.Create;
SL.Delimiter := '|';
SL.QuoteChar := '"';
SL.StrictDelimiter := True;
SL.DelimitedText := 'O=0 | ! .!=!.!';
Temp := 'Count: ' + IntToStr(SL.Count) + #13;
for i := 0 to SL.Count - 1 do
Temp := Temp + Format('Name: %s Value: %s'#13,
[SL.Names[i], SL.ValueFromIndex[i]]);
ShowMessage(Temp);
end;
This produces this output:
TStringList Names/Values probably isn't going to do what you need. It's not clear what your actual goal is, but it appears that a simple text file with a simple list of text|replacement and plain parsing of that file would work, and you can easily use TStringList to read/write from that file, but I don't see any way to do the parsing easily except to do it yourself. You could use an array to store the pairs when you parse them:
type
TReplacePair = record
TextValue: string;
ReplaceValue: string;
end;
TReplacePairs = array of TReplacePair;
function GetReplacementPairs: TReplacePairs;
var
ConfigInfo: TStringList;
i, Split: Integer;
begin
ConfigInfo := TStringList.Create;
try
ConfigInfo.LoadFromFile('ReplacementPairs.txt');
SetLength(Result, ConfigInfo.Count);
for i := 0 to ConfigInfo.Count - 1 do
begin
Split := Pos('|`, ConfigInfo[i];
Result[i].TextValue := Copy(ConfigInfo[i], 1, Split - 1);
Result[i].ReplaceValue := Copy(ConfigInfo[i], Split + 1, MaxInt);
end;
finally
ConfigInfo.Free;
end;
end;
You can then populate whatever controls you need to edit/add/delete the replacement pairs, and just reverse the read operation to write them back out to save.

Getting the whole word (link) from a phrase, when I know some of it

Lets say I have a String: Go to this page: http://mysite.com/?page=1 , and I have a string page. I would like to create a function like so:
MyBoolean := IsLink('Go to this page: http://mysite.com/?page=1','page',sLink);
// sLink is a Var, so it would return http://mysite.com/?page=1
Basically it is supposed to check if the word "page" is part of a link or not.
However I just can't figure it out. Any tips?
You could do something like
function GetLinkContaining(const Str, SubStr: string; out URL: string): boolean;
const
ValidURLSpecialChars = ['.', ':', '/', '?', '=', '&', '%'];
Prefixes: array[0..4] of string = ('http://', 'https://', 'ftp://', 'mailto:',
'www.');
function IsValidURLChar(const Char: char): boolean;
begin
result := IsLetterOrDigit(Char) or (Char in ValidURLSpecialChars);
end;
var
SubStrPos: integer;
Start, &End: integer;
i: Integer;
URLBegin: integer;
begin
result := false;
URLBegin := 0;
for i := low(Prefixes) to High(Prefixes) do
begin
URLBegin := Pos(Prefixes[i], Str);
if URLBegin > 0 then
break;
end;
if URLBegin = 0 then Exit(false);
SubStrPos := PosEx(SubStr, Str, URLBegin);
if SubStrPos = 0 then Exit(false);
Start := SubStrPos;
for i := SubStrPos - 1 downto 1 do
if IsValidURLChar(Str[i]) then
dec(Start)
else
break;
&End := SubStrPos + length(SubStr);
for i := SubStrPos + length(SubStr) to length(Str) do
if IsValidURLChar(Str[i]) then
inc(&End)
else
break;
URL := Copy(Str, Start, &End - Start);
result := true;
end;
To test it:
procedure TForm1.FormCreate(Sender: TObject);
var
s: string;
begin
if GetLinkContaining('Go to this page: http://mysite.com/?page=1 (right now!)',
'page', s) then
ShowMessage(s);
if GetLinkContaining('This is my favourite site (www.bbc.co.uk).', 'bbc', s) then
ShowMessage(s);
end;
To check if 'page' is part of a string you can use the function Pos.
function Pos(Str, Source : string): integer;
Pos returns an integer specifying the position of the first occurrence of one string within another.
Pos looks for the first complete occurence of Str in Source. If it finds one, it returns the character position in Source of the first character in Str as an integer value, otherwise it returns 0. Pos is case sensitive. So mybe you have to deal with upper- and lowe-case situations.
To extracrt the URL is (maybe) not so easy, you have to define more conditions. If the URL is always at the end of your string, you can copy everything from the http on (also use Pos and Copy!)
Among the more powerful string matching algorithms there are regular expressions. They allow for very complex matches without writing much code, although mastering them may require a little time. Latest versions of Delphi have already regular expression libraries, but you can find some for earlier versions as well.

Resources