Core Function StrNew

From Sputnik Wiki
(Difference between revisions)
Jump to: navigation, search
(Description)
Line 5: Line 5:
 
=== Description ===
 
=== Description ===
  
Create a new string of a given length filled with a given char (or optionally return it as a CharPtr rather than a new string.
+
Create a new string of a given length filled with a given char (or optionally return it as a CharPtr rather than a new string).
  
 
=== Parameters ===
 
=== Parameters ===

Revision as of 13:50, 18 September 2015

StrNew( <char>, <length>, <flag>

Contents

Description

Create a new string of a given length filled with a given char (or optionally return it as a CharPtr rather than a new string).

Parameters

char

length

flag

Optional; Choose if you want to return as a normal string or a CharPtr

true -- Return as CharPtr

false -- Return as string

Default: false

Return Value

Success: If the flag is TRUE then return will be a CharPtr. If the flag is FALSE then return will be a normal string

Failure: null

Remarks

If the FLAG is true memory will be allocated and the pointer returned to the memory you must use Free() command to reclaim that memory after you are finished with it, You can of course convert it to a string using (string) cast then immediately free the CharPtr.

One benefit of this function is it will create the String/CharPtr in the correct memory size and type that Sputnik uses for Strings (should be in UTF8 format so 2 bytes per char with a zero terminator 2 bytes long).

Example

Normal string

$Str = StrNew('T', 15);
$Str[0] = 'A'; // Set first char to A
$Str[1] = 'A'; // Set second char to B
echo $Str; // Prints: ABTTTTTTTTTTTTT
// Of course you could just make the string like
// $Str = "ABTTTTTTTTTTTTT";
// OR
// $Str = "AB" . ('T' x 13);
// The purpose of this function is just to make it more
// simple to create a string for use in Fixed() and (char*) etc

Example of TRUE flag and converting the return to string once done with it

// Create pointer to a newly created string containing '5' chars of 'A'
// the return will be as a CharPtr rather than a normal string
$PTR = StrNew('A', 5, true);
*$PTR = 'T'; // Set first character to T
$PTR[1] = 'B'; // Set second character to B
$STR = (string)$PTR; // Convert the CharPtr to a string
free($PTR); // Free the CharPtr as it is no longer needed
printr( $STR ); // Prints TBAAA
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox