reference

This documentation is automatically generated from the openFrameworks source code using doxygen and refers to the most recent release, version 0.12.0.

ofUtils.h File Reference
#include "ofConstants.h"
#include "utf8.h"
#include <bitset>
#include <chrono>
#include <iomanip>
#include <algorithm>
#include <sstream>
#include <type_traits>
#include <random>
#include "ofRandomEngine.h"
#include "ofRandomDistributions.h"

Go to the source code of this file.

Classes

struct  ofTime
 
class  ofUTF8Iterator
 Iterate through each Unicode codepoint in a UTF8-encoded std::string. More...
 

Functions

void ofResetElapsedTimeCounter ()
 Reset the elapsed time counter.
 
float ofGetElapsedTimef ()
 Get the elapsed time in seconds.
 
uint64_t ofGetUnixTimeMillis ()
 Get the Unix Time in milliseconds.
 
uint64_t ofGetElapsedTimeMillis ()
 Get the elapsed time in milliseconds.
 
uint64_t ofGetElapsedTimeMicros ()
 Get the elapsed time in microseconds.
 
uint64_t ofGetFrameNum ()
 Get the number of frames rendered since the program started.
 
int ofGetSeconds ()
 Get the seconds after the minute.
 
int ofGetMinutes ()
 Get minutes after the hour.
 
int ofGetHours ()
 Get the hour of the day.
 
uint64_t ofGetUnixTime ()
 Get the number of seconds since Midnight, January 1, 1970.
 
 OF_DEPRECATED_MSG ("Use ofGetSystemTimeMillis() instead", uint64_t ofGetSystemTime())
 Get the system time in milliseconds (system uptime).
 
uint64_t ofGetSystemTimeMillis ()
 Get the system time in milliseconds (system uptime).
 
uint64_t ofGetSystemTimeMicros ()
 Get the system time in microseconds (system uptime).
 
ofTime ofGetCurrentTime ()
 Get the system time.
 
void ofSleepMillis (int millis)
 Sleeps the current thread for the specified amount of milliseconds.
 
std::string ofGetTimestampString ()
 Formats the current system time according to the given format.
 
std::string ofGetTimestampString (const std::string &timestampFormat)
 Formats the current system time according to the given format.
 
int ofGetYear ()
 Get the current year.
 
int ofGetMonth ()
 Get the current month.
 
int ofGetDay ()
 Get the current day within the month.
 
int ofGetWeekday ()
 Get the current weekday.
 
template<typename ... Args>
void ofShuffle (Args &&... args)
 Randomly reorder the values in a container.
 
template<class T >
void ofRandomize (std::vector< T > &values)
 Randomly reorder the values in a vector.
 
template<class T , class BoolFunction >
void ofRemove (std::vector< T > &values, BoolFunction shouldErase)
 Conditionally remove values from a vector.
 
template<class T >
void ofSort (std::vector< T > &values)
 Sort a vector of values into ascending order.
 
template<class T , class BoolFunction >
void ofSort (std::vector< T > &values, BoolFunction compare)
 Sort a vector of values into an order defined by a comparator.
 
template<class T >
std::size_t ofFind (const std::vector< T > &values, const T &target)
 Search for a target value in a vector of values.
 
template<class T >
bool ofContains (const std::vector< T > &values, const T &target)
 Search for a target value in a vector of values.
 
std::vector< std::string > ofSplitString (const std::string &source, const std::string &delimiter, bool ignoreEmpty=false, bool trim=false)
 Splits a string using a delimiter.
 
std::string ofJoinString (const std::vector< std::string > &stringElements, const std::string &delimiter)
 Join a vector of strings together into one string.
 
void ofStringReplace (std::string &input, const std::string &searchStr, const std::string &replaceStr)
 Replace all occurrences of a string with another string.
 
bool ofIsStringInString (const std::string &haystack, const std::string &needle)
 Check if string contains another string.
 
std::size_t ofStringTimesInString (const std::string &haystack, const std::string &needle)
 Check how many times a string contains another string.
 
std::string ofToLower (const std::string &src, const std::string &locale="")
 Converts all characters in a string to lowercase.
 
std::string ofToUpper (const std::string &src, const std::string &locale="")
 Converts all characters in the string to uppercase.
 
std::string ofTrimFront (const std::string &src, const std::string &locale="")
 Remove locale-defined whitespace from the beginning of a string.
 
std::string ofTrimBack (const std::string &src, const std::string &locale="")
 Remove locale-defined whitespace from the end of a string.
 
std::string ofTrim (const std::string &src, const std::string &locale="")
 Remove locale-defined whitespace from the beginning and end of a string.
 
 OF_DEPRECATED_MSG ("Use ofUTF8Append instead", void ofAppendUTF8(std::string &str, uint32_t utf8))
 
void ofUTF8Append (std::string &utf8, uint32_t codepoint)
 Append a Unicode codepoint to a UTF8-encoded std::string.
 
void ofUTF8Insert (std::string &utf8, size_t pos, uint32_t codepoint)
 Insert a Unicode codepoint into a UTF8-encoded string at a position.
 
void ofUTF8Erase (std::string &utf8, size_t pos, size_t len)
 Erase a range of codepoints from a UTF8-encoded substring.
 
std::string ofUTF8Substring (const std::string &utf8, size_t pos, size_t len)
 Extract a range of codepoints from as a std::string.
 
std::string ofUTF8ToString (uint32_t codepoint)
 Convert a Unicode codepoint to a UTF8-encoded std::string.
 
size_t ofUTF8Length (const std::string &utf8)
 Get the number of Unicode code points in a UTF8-encoded string.
 
template<typename ... Args>
std::string ofVAArgsToString (const char *format, Args &&... args)
 Convert a variable length argument to a string.
 
template<class T >
std::string ofToString (const T &value)
 Convert a value to a string.
 
template<class T >
std::string ofToString (const T &value, int precision)
 Convert a value to a string with a specific precision.
 
template<class T >
std::string ofToString (const T &value, int width, char fill)
 Convert a value to a string with a specific width and fill.
 
template<class T >
std::string ofToString (const T &value, int precision, int width, char fill)
 Convert a value to a string with a specific precision, width and filll.
 
template<class T >
std::string ofToString (const std::vector< T > &values)
 Convert a vector of values to a comma-delimited string.
 
template<class T >
ofFromString (const std::string &value)
 Convert a string represetnation to another type.
 
template<>
std::string ofFromString (const std::string &value)
 Convert a string represetnation to another string.
 
template<>
const char * ofFromString (const std::string &value)
 Convert a string represetnation to another string.
 
template<typename T >
ofTo (const std::string &str)
 Convert a string to a given data type.
 
int ofToInt (const std::string &intString)
 Convert a string to an integer.
 
int64_t ofToInt64 (const std::string &intString)
 Convert a string to a int64_t.
 
float ofToFloat (const std::string &floatString)
 Convert a string to a float.
 
double ofToDouble (const std::string &doubleString)
 Convert a string to a double.
 
bool ofToBool (const std::string &boolString)
 Convert a string to a boolean.
 
template<class T >
std::string ofToHex (const T &value)
 Converts any value to its equivalent hexadecimal representation.
 
template<>
std::string ofToHex (const std::string &value)
 Convert a string to a hexadecimal string.
 
std::string ofToHex (const char *value)
 Convert a c-style string to a hexadecimal string.
 
int ofHexToInt (const std::string &intHexString)
 Convert a string representing an integer in hexadecimal to a string.
 
char ofHexToChar (const std::string &charHexString)
 Convert a string representing an char in hexadecimal to a char.
 
float ofHexToFloat (const std::string &floatHexString)
 Convert a string representing an float in hexadecimal to a float.
 
std::string ofHexToString (const std::string &stringHexString)
 Convert a string representing an string in hexadecimal to a string.
 
char ofToChar (const std::string &charString)
 Convert a string representation of a char to a actual char.
 
template<class T >
std::string ofToBinary (const T &value)
 Converts any datatype value to a string of only 1s and 0s.
 
template<>
std::string ofToBinary (const std::string &value)
 Converts a string value to a string of only 1s and 0s.
 
std::string ofToBinary (const char *value)
 Converts a c-style string to a string of only 1s and 0s.
 
int ofBinaryToInt (const std::string &value)
 Convert a binary string to an int.
 
char ofBinaryToChar (const std::string &value)
 Convert a binary string to an char.
 
float ofBinaryToFloat (const std::string &value)
 Convert a binary string to a float.
 
std::string ofBinaryToString (const std::string &value)
 Convert a binary string to ASCII characters.
 
std::string ofGetVersionInfo ()
 Get the current version of openFrameworks as a string.
 
unsigned int ofGetVersionMajor ()
 Get the major version number of openFrameworks.
 
unsigned int ofGetVersionMinor ()
 Get the minor version number of openFrameworks.
 
unsigned int ofGetVersionPatch ()
 Get the patch version number of openFrameworks.
 
std::string ofGetVersionPreRelease ()
 Get the pre-release version of openFrameworks.
 
void ofSaveScreen (const std::string &filename)
 Saves the current screen image to a file on disk.
 
void ofSaveFrame (bool bUseViewport=false)
 Saves the current frame as a PNG image.
 
void ofSaveViewport (const std::string &filename)
 Saves the current viewport as an image.
 
void ofLaunchBrowser (const std::string &url, bool uriEncodeQuery=false)
 Launch the given URL in the default browser.
 
std::string ofSystem (const std::string &command)
 Executes a system command. Similar to run a command in terminal.
 
ofTargetPlatform ofGetTargetPlatform ()
 Get the target platform of the current system.
 
std::string ofGetEnv (const std::string &var, const std::string defaultValue="")
 Get the value of a given environment variable.
 

Function Documentation

◆ OF_DEPRECATED_MSG() [1/2]

OF_DEPRECATED_MSG ( "Use ofGetSystemTimeMillis() instead"  ,
uint64_t   ofGetSystemTime() 
)

Get the system time in milliseconds (system uptime).

Returns
the system time in milliseconds.

◆ OF_DEPRECATED_MSG() [2/2]

OF_DEPRECATED_MSG ( "Use ofUTF8Append instead"  ,
void   ofAppendUTF8std::string &str, uint32_t utf8 
)

◆ ofBinaryToChar()

char ofBinaryToChar ( const std::string &  value)

Convert a binary string to an char.

Interprets a string consisting only of 1s and 0s as an char and returns the corresponding int value.

\value The binary string.

Returns
the char represented by the string or 0 on failure.

◆ ofBinaryToFloat()

float ofBinaryToFloat ( const std::string &  value)

Convert a binary string to a float.

Interprets a string consisting only of 1s and 0s as an a float (little-endian, 32-bit IEEE 754), and returns the corresponding float value.

\value The binary string.

Returns
the float represented by the string or 0 on failure.

◆ ofBinaryToInt()

int ofBinaryToInt ( const std::string &  value)

Convert a binary string to an int.

Interprets a string consisting only of 1s and 0s as an int (little-endian, 32-bit), and returns the corresponding int value.

\value The binary string.

Returns
the integer represented by the string or 0 on failure.

◆ ofBinaryToString()

std::string ofBinaryToString ( const std::string &  value)

Convert a binary string to ASCII characters.

Interprets a string consisting only of 1s and 0s as 8-bit ASCII characters and returns the corresponding string.

\value The binary string.

Returns
the ASCII string represented by the string.

◆ ofContains()

template<class T >
bool ofContains ( const std::vector< T > &  values,
const T &  target 
)

Search for a target value in a vector of values.

Template Parameters
Tthe type contained by the vector.
Parameters
valuesThe vector of values to be searched.
targetThe target value to be found.
Returns
true if at least one value equal to the target value is found.

◆ ofFind()

template<class T >
std::size_t ofFind ( const std::vector< T > &  values,
const T &  target 
)

Search for a target value in a vector of values.

Template Parameters
Tthe type contained by the vector.
Parameters
valuesThe vector of values to be searched.
targetThe target value to be found.
Returns
true the index of the first target value found.
See also
http://www.cplusplus.com/reference/iterator/distance/

◆ ofFromString() [1/3]

template<class T >
T ofFromString ( const std::string &  value)

Convert a string represetnation to another type.

Often, this method will be used to convert a string to a numerical type.

Template Parameters
TThe target data type.
Parameters
valueThe string value to convert to type T.
Returns
the string converted to the target data type T.

◆ ofFromString() [2/3]

template<>
std::string ofFromString ( const std::string &  value)

Convert a string represetnation to another string.

Parameters
valueThe string value to convert to another string.
Returns
the string converted to another string.

◆ ofFromString() [3/3]

template<>
const char * ofFromString ( const std::string &  value)

Convert a string represetnation to another string.

Equivalent to calling the .c_str() on a std::string.

Parameters
valueThe string value to convert to another string.
Returns
the string converted to a c-style string.

◆ ofGetCurrentTime()

ofTime ofGetCurrentTime ( )

Get the system time.

Returns
the system time, which is the time since the system booted (uptime).

◆ ofGetDay()

int ofGetDay ( )

Get the current day within the month.

Returns
the day witin the month [1-31].

◆ ofGetElapsedTimef()

float ofGetElapsedTimef ( )

Get the elapsed time in seconds.

This returns the elapsed time since ofResetElapsedTimeCounter() was called. Usually ofResetElapsedTimeCounter() is called automatically once during program startup.

Returns
the floating point elapsed time in seconds.

◆ ofGetElapsedTimeMicros()

uint64_t ofGetElapsedTimeMicros ( )

Get the elapsed time in microseconds.

This returns the elapsed time since ofResetElapsedTimeCounter() was called. Usually ofResetElapsedTimeCounter() is called automatically upon program startup.

Returns
the elapsed time in microseconds (1000000 microseconds = 1 second).

◆ ofGetElapsedTimeMillis()

uint64_t ofGetElapsedTimeMillis ( )

Get the elapsed time in milliseconds.

This returns the elapsed time since ofResetElapsedTimeCounter() was called. Usually ofResetElapsedTimeCounter() is called automatically once during program startup.

Returns
the elapsed time in milliseconds (1000 milliseconds = 1 second).

◆ ofGetEnv()

std::string ofGetEnv ( const std::string &  var,
const std::string  defaultValue = "" 
)

Get the value of a given environment variable.

Note
The available environment variables differ between operating systems.
Parameters
varthe environment variable name.
defaultValuethe value to return if the environment variable is not set. defaults to empty string.
Returns
the environmnt variable's value or the provided default value if not found.

◆ ofGetFrameNum()

uint64_t ofGetFrameNum ( )

Get the number of frames rendered since the program started.

Returns
the number of frames rendered since the program started.

◆ ofGetHours()

int ofGetHours ( )

Get the hour of the day.

Returns
the hour of the day [0-23].

◆ ofGetMinutes()

int ofGetMinutes ( )

Get minutes after the hour.

Returns
the minutes after the hour [0-59].

◆ ofGetMonth()

int ofGetMonth ( )

Get the current month.

Returns
the current month [1-12].

◆ ofGetSeconds()

int ofGetSeconds ( )

Get the seconds after the minute.

Time

Returns
the seconds after the minute [0-59].

◆ ofGetSystemTimeMicros()

uint64_t ofGetSystemTimeMicros ( )

Get the system time in microseconds (system uptime).

Returns
the system time in microseconds.

◆ ofGetSystemTimeMillis()

uint64_t ofGetSystemTimeMillis ( )

Get the system time in milliseconds (system uptime).

Returns
the system time in milliseconds.

◆ ofGetTargetPlatform()

ofTargetPlatform ofGetTargetPlatform ( )

Get the target platform of the current system.

Returns
the current ofTargetPlatform.

◆ ofGetTimestampString() [1/2]

std::string ofGetTimestampString ( )

Formats the current system time according to the given format.

The default timestamp format is "%Y-%m-%d-%H-%M-%S-%i" (e.g. 2011-01-15-18-29-35-299).

Returns
the current time as a string with the default format.

◆ ofGetTimestampString() [2/2]

std::string ofGetTimestampString ( const std::string &  timestampFormat)

Formats the current system time according to the given format.

The format string is used as a template to format the date and is copied character by character except for the following special characters, which are replaced by the corresponding value.

  • w - abbreviated weekday (Mon, Tue, ...)
  • W - full weekday (Monday, Tuesday, ...)
  • b - abbreviated month (Jan, Feb, ...)
  • B - full month (January, February, ...)
  • d - zero-padded day of month (01 .. 31)
  • e - day of month (1 .. 31)
  • f - space-padded day of month ( 1 .. 31)
  • m - zero-padded month (01 .. 12)
  • n - month (1 .. 12)
  • o - space-padded month ( 1 .. 12)
  • y - year without century (70)
  • Y - year with century (1970)
  • H - hour (00 .. 23)
  • h - hour (00 .. 12)
  • a - am/pm
  • A - AM/PM
  • M - minute (00 .. 59)
  • S - second (00 .. 59)
  • s - seconds and microseconds (equivalent to S.F)
  • i - millisecond (000 .. 999)
  • c - centisecond (0 .. 9)
  • F - fractional seconds/microseconds (000000 - 999999)
  • z - time zone differential in ISO 8601 format (Z or +NN.NN)
  • Z - time zone differential in RFC format (GMT or +NNNN)
  • %% - percent sign
Parameters
timestampFormatThe formatting pattern.
Returns
the formatted timestamp as a string.
Warning
an invalid timestampFormat may crash windows apps.

◆ ofGetUnixTime()

uint64_t ofGetUnixTime ( )

Get the number of seconds since Midnight, January 1, 1970.

Resolution is in seconds.

Returns
the number of seconds since Midnight, January 1, 1970 (epoch time).

◆ ofGetUnixTimeMillis()

uint64_t ofGetUnixTimeMillis ( )

Get the Unix Time in milliseconds.

This returns the milliseconds since Midnight, January 1, 1970.

Returns
the milliseconds since Midnight, January 1, 1970.

◆ ofGetVersionInfo()

std::string ofGetVersionInfo ( )

Get the current version of openFrameworks as a string.

Version

openFrameworks uses the semantic versioning system.

See also
http://semver.org/
Returns
The string representation of the version (e.g. 0.9.0).

◆ ofGetVersionMajor()

unsigned int ofGetVersionMajor ( )

Get the major version number of openFrameworks.

openFrameworks uses the semantic versioning system.

See also
http://semver.org/
Returns
The major version number.

◆ ofGetVersionMinor()

unsigned int ofGetVersionMinor ( )

Get the minor version number of openFrameworks.

openFrameworks uses the semantic versioning system.

See also
http://semver.org/
Returns
The minor version number.

◆ ofGetVersionPatch()

unsigned int ofGetVersionPatch ( )

Get the patch version number of openFrameworks.

openFrameworks uses the semantic versioning system.

See also
http://semver.org/
Returns
The patch version number.

◆ ofGetVersionPreRelease()

std::string ofGetVersionPreRelease ( )

Get the pre-release version of openFrameworks.

openFrameworks uses the semantic versioning system.

For pre-release versions of openFrameworks, including development versions, this string will describe the pre-release state. Examples might include "master", "rc1", "rc2", etc. For all stable releases, this string will be empty.

See also
http://semver.org/
Returns
The pre-release version string.

◆ ofGetWeekday()

int ofGetWeekday ( )

Get the current weekday.

Values 0 = Sunday, 1 = Monday, ..., 6 = Saturday.

Returns
the current weekday [0-6].

◆ ofGetYear()

int ofGetYear ( )

Get the current year.

Returns
the current year.

◆ ofHexToChar()

char ofHexToChar ( const std::string &  charHexString)

Convert a string representing an char in hexadecimal to a char.

Converts a hexadecimal representation of an char (e.g., "61") to an actual char (e.g., a).

Parameters
charHexStringThe string representing an char in hexadecimal.
Returns
the char represented by the string.

◆ ofHexToFloat()

float ofHexToFloat ( const std::string &  floatHexString)

Convert a string representing an float in hexadecimal to a float.

Converts a hexadecimal representation of an float (little-endian, 32-bit IEEE 754, e.g., "43000000") to an actual float (e.g., 128.f).

Parameters
floatHexStringThe string representing an float in hexadecimal.
Returns
the float represented by the string.

◆ ofHexToInt()

int ofHexToInt ( const std::string &  intHexString)

Convert a string representing an integer in hexadecimal to a string.

Converts a hexadecimal representation of an int (little-endian, 32-bit, e.g., "0xbadf00d" or "badf00d") to an actual int.

Parameters
intHexStringThe string representing an integer in hexadecimal.
Returns
the integer represented by the string.

◆ ofHexToString()

std::string ofHexToString ( const std::string &  stringHexString)

Convert a string representing an string in hexadecimal to a string.

Converts a hexadecimal representation of an string (e.g., "61626364656667") to an actual string ("abcdefg").

Parameters
stringHexStringThe string representing an string in hexadecimal.
Returns
the string represented by the string.

◆ ofIsStringInString()

bool ofIsStringInString ( const std::string &  haystack,
const std::string &  needle 
)

Check if string contains another string.

Example:

std::string haystack = "foobar";
ofLog() << ofIsStringInString(haystack, "foo"); // Outputs 1.
ofLog() << ofIsStringInString(haystack,"bar"); // Outputs 1.
ofLog() << ofIsStringInString(haystack, "something else"); // Outputs 0.
A C++ stream-style logging interface.
Definition ofLog.h:299
bool ofIsStringInString(const string &haystack, const string &needle)
Definition ofUtils.cpp:696
Parameters
haystackThe string to check for occurrence in.
needleThe string to check for.

◆ ofJoinString()

std::string ofJoinString ( const std::vector< std::string > &  stringElements,
const std::string &  delimiter 
)

Join a vector of strings together into one string.

Parameters
stringElementsThe vector of strings to join.
delimiterThe delimiter to put betweeen each string.

◆ ofLaunchBrowser()

void ofLaunchBrowser ( const std::string &  url,
bool  uriEncodeQuery = false 
)

Launch the given URL in the default browser.

Time

Parameters
urlthe URL to open.
uriEncodeQuerytrue if the query parameters in the given URL have already been URL encoded.

◆ ofRandomize()

template<class T >
void ofRandomize ( std::vector< T > &  values)

Randomly reorder the values in a vector.

Vectors

Template Parameters
Tthe type contained by the vector.
Parameters
valuesThe vector of values to modify.

◆ ofRemove()

template<class T , class BoolFunction >
void ofRemove ( std::vector< T > &  values,
BoolFunction  shouldErase 
)

Conditionally remove values from a vector.

Values are removed if, when passed to the BoolFunction, the BoolFunction function returns true. The given BoolFunction can be a custom function or a built-in function.

Example of a custom function to remove odd numbers from a std::vector<int> of integers:

bool IsOdd(int i) {
return ((i % 2) == 1);
}

To call the function, one might use:

std::vector<int> myInts;
// Fill the vector with integers.
for (int i = 0; i < 10; ++i)
{
myInts.push_back(i);
}
ofRemove(myInts, IsOdd);
void ofRemove(std::vector< T > &values, BoolFunction shouldErase)
Conditionally remove values from a vector.
Definition ofUtils.h:284

The resulting vector will contain the following values:

0, 2, 4, 6, 8

Template Parameters
Tthe type contained by the vector.
BoolFunctionthe boolean function used to erase.
Parameters
valuesThe vector of values to modify.
shouldEraseA boolean function as described above.
See also
http://www.cplusplus.com/reference/algorithm/remove_if/

◆ ofResetElapsedTimeCounter()

void ofResetElapsedTimeCounter ( )

Reset the elapsed time counter.

Time

This method resets the times returned by ofGetElapsedTimef(), ofGetElapsedTimeMillis() and ofGetElapsedTimeMicros() to zero.

Note
This is called on the first frame during app startup.

◆ ofSaveFrame()

void ofSaveFrame ( bool  bUseViewport = false)

Saves the current frame as a PNG image.

The PNG image will be named according to an internal counter in sequence. The count will be restarted each time the program is restarted.

Parameters
bUseViewportSet to true if the current viewport should be used.

◆ ofSaveScreen()

void ofSaveScreen ( const std::string &  filename)

Saves the current screen image to a file on disk.

Saving

Example:

ofSaveScreen("screen.png"); // Will save screen.png in the /data folder.
void ofSaveScreen(const string &filename)
Definition ofUtils.cpp:1007

The output file type will be deduced from the given file name.

Parameters
filenameThe image output file.

◆ ofSaveViewport()

void ofSaveViewport ( const std::string &  filename)

Saves the current viewport as an image.

The output file type will be deduced from the given file name.

Parameters
filenameThe image output file.

◆ ofShuffle()

template<typename ... Args>
void ofShuffle ( Args &&...  args)

Randomly reorder the values in a container.

Containers

Template Parameters
TAny container that meets std::shuffle's requirements which are: ValueSwappable and LegacyRandomAccessIterator.

◆ ofSleepMillis()

void ofSleepMillis ( int  millis)

Sleeps the current thread for the specified amount of milliseconds.

Parameters
millisThe number of millseconds to sleep.

◆ ofSort() [1/2]

template<class T >
void ofSort ( std::vector< T > &  values)

Sort a vector of values into ascending order.

The elements are compared using operator< for the first version. Equivalent elements are not guaranteed to keep their original relative order.

Template Parameters
Tthe type contained by the vector.
Parameters
valuesThe vector of values to be sorted.
See also
http://www.cplusplus.com/reference/algorithm/sort/

◆ ofSort() [2/2]

template<class T , class BoolFunction >
void ofSort ( std::vector< T > &  values,
BoolFunction  compare 
)

Sort a vector of values into an order defined by a comparator.

Example of a custom function to sort descending of integers:

bool sortDescending(int i, int j)
{
return (j < i);
}

This binary function must accept two elements in the range as arguments and return a value convertible to bool. The value returned indicates whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines. The function shall not modify any of its arguments. This can either be a function pointer or a function object.

To call the function, one might use:

std::vector<int> myInts;
// Fill the vector with integers.
for (int i = 0; i < 10; ++i)
{
myInts.push_back(i);
}
ofSort(myInts, sortDescending);
void ofSort(std::vector< T > &values)
Sort a vector of values into ascending order.
Definition ofUtils.h:298

The resulting vector will contain the following values:

9, 8, 7, 6, 5, 4, 3, 2, 1, 0.

Template Parameters
Tthe type contained by the vector.
Parameters
valuesThe vector of values to be sorted.
compareThe comparison function.
See also
http://www.cplusplus.com/reference/algorithm/sort/

◆ ofSplitString()

std::vector< std::string > ofSplitString ( const std::string &  source,
const std::string &  delimiter,
bool  ignoreEmpty = false,
bool  trim = false 
)

Splits a string using a delimiter.

Manipulation

ofSplitString splits a string and returns the collection of string tokens inside of a std::vector<std::string>.

A useful application is to use delimiter " ":

result = ofSplitString("of rocks", " ");
// result[0] = "of"
// result[1] = "rocks"
vector< string > ofSplitString(const string &source, const string &delimiter, bool ignoreEmpty, bool trim)
Definition ofUtils.cpp:636

Like this a big string can be "cut" and turned it into a collection of words. The user can also ignore empty tokens. Empty tokens occur when a there are multiple delimiters in a row (e.g. "of,rocks,,!"). The user can also "trim" the tokens. This will remove whitespace from before and after each token. This might be useful when a delimted string is padded with with spaces (e.g. "of , rocks ,!").

Parameters
sourceThe string to split.
delimiterThe delimiter string.
ignoreEmptySet to true to remove empty tokens.
trimSet to true to trim the resulting tokens.
Returns
A vector of strings split with the delimiter.

◆ ofStringReplace()

void ofStringReplace ( std::string &  input,
const std::string &  searchStr,
const std::string &  replaceStr 
)

Replace all occurrences of a string with another string.

Note
The input string is passed by reference, so it will be modified.
Parameters
inputThe string to run the replacement on.
searchStrThe string to be replaced.
replaceStrThe string to put in place.

◆ ofStringTimesInString()

std::size_t ofStringTimesInString ( const std::string &  haystack,
const std::string &  needle 
)

Check how many times a string contains another string.

Parameters
haystackThe string to check for occurrence in .
needleThe string to check for.

◆ ofSystem()

std::string ofSystem ( const std::string &  command)

Executes a system command. Similar to run a command in terminal.

Note
Will block until the executed program/command has finished.
Returns
the system command output as string.
Note
ofSystem() grabs only stdout; if you are interested in stderr (which may be the case if you're getting "empty" results) consider redirection by appending 2>&1|cat to your command.

◆ ofTo()

template<typename T >
T ofTo ( const std::string &  str)

Convert a string to a given data type.

Template Parameters
TThe return type.
Parameters
valueThe string value to convert to a give type.
Returns
the string converted to the type.

◆ ofToBinary() [1/3]

std::string ofToBinary ( const char *  value)

Converts a c-style string to a string of only 1s and 0s.

The corresponding string of 1s and 0s corresponds to the way value is stored in memory.

Parameters
valueThe c-style string to convert to a binary string.
Returns
a binary string.

◆ ofToBinary() [2/3]

template<>
std::string ofToBinary ( const std::string &  value)

Converts a string value to a string of only 1s and 0s.

The corresponding string of 1s and 0s corresponds to the way value is stored in memory.

Parameters
valueThe string to convert to a binary string.
Returns
a binary string.

◆ ofToBinary() [3/3]

template<class T >
std::string ofToBinary ( const T &  value)

Converts any datatype value to a string of only 1s and 0s.

The corresponding string of 1s and 0s corresponds to the way value is stored in memory.

Template Parameters
TThe data type of the value to convert to a binary string.
Parameters
valueThe data to convert to a binary string.
Returns
a binary string.

◆ ofToBool()

bool ofToBool ( const std::string &  boolString)

Convert a string to a boolean.

Converts a std::string representation of a boolean (e.g., "TRUE") to an actual bool using a case-insensitive comparison against the words "true" and "false".

Parameters
boolStringThe string representation of the boolean.
Returns
the boolean represented by the string or 0 on failure.

◆ ofToChar()

char ofToChar ( const std::string &  charString)

Convert a string representation of a char to a actual char.

Converts a string representation of a single char (e.g., "c") to an actual char.

Note
Multi-byte chars and multi-char strings are not supported.
Parameters
charStringThe char string to convert.
Returns
The string as a char or 0 on failure.

◆ ofToDouble()

double ofToDouble ( const std::string &  doubleString)

Convert a string to a double.

Converts a std::string representation of a double (e.g., "3.14") to an actual double.

Parameters
doubleStringThe string representation of the double.
Returns
the double represented by the string or 0 on failure.

◆ ofToFloat()

float ofToFloat ( const std::string &  floatString)

Convert a string to a float.

Converts a std::string representation of a float (e.g., "3.14") to an actual float.

Parameters
floatStringstring representation of the float.
Returns
the float represented by the string or 0 on failure.

◆ ofToHex() [1/3]

std::string ofToHex ( const char *  value)

Convert a c-style string to a hexadecimal string.

Converts a string (e.g., "abc") to its equivalent hexadecimal representation (e.g., "616263").

Parameters
valueThe value to convert to a hexadecimal string.
Returns
a hexadecimal string.

◆ ofToHex() [2/3]

template<>
std::string ofToHex ( const std::string &  value)

Convert a string to a hexadecimal string.

Converts a string (e.g., "abc") to its equivalent hexadecimal representation (e.g., "616263").

Parameters
valueThe value to convert to a hexadecimal string.
Returns
a hexadecimal string.

◆ ofToHex() [3/3]

template<class T >
std::string ofToHex ( const T &  value)

Converts any value to its equivalent hexadecimal representation.

The hexadecimal representation corresponds to the way a number is stored in memory.

Template Parameters
TThe data type of the value to convert to a hexadecimal string.
Parameters
valueThe value to convert to a hexadecimal string.
Returns
the hexadecimal string representation of the value.

◆ ofToInt()

int ofToInt ( const std::string &  intString)

Convert a string to an integer.

Conversion

Converts a std::string representation of an int (e.g., "3") to an actual int.

Parameters
intStringThe string representation of the integer.
Returns
the integer represented by the string or 0 on failure.

◆ ofToInt64()

int64_t ofToInt64 ( const std::string &  intString)

Convert a string to a int64_t.

Converts a std::string representation of a long integer (e.g., "9223372036854775807") to an actual int64_t.

Parameters
intStringThe string representation of the long integer.
Returns
the long integer represented by the string or 0 on failure.

◆ ofToLower()

std::string ofToLower ( const std::string &  src,
const std::string &  locale = "" 
)

Converts all characters in a string to lowercase.

This function expects a UTF-8 encoded multi-byte string to be passed. Resulting strings will be returned as UTF-8 encoded multi-byte strings.

std::string enthusiasticGreeting = "HELLO, WORLD!";
std::string politeGreeting = ofToLower(enthusiasticGreeting);
ofLog() << politeGreeting; // Returns "hello, world!"
string ofToLower(const string &src, const string &locale)
Definition ofUtils.cpp:784
Parameters
srcThe UTF-8 encoded string to convert to lowercase.
Returns
the UTF-8 encoded string as all lowercase characters.

◆ ofToString() [1/5]

template<class T >
std::string ofToString ( const std::vector< T > &  values)

Convert a vector of values to a comma-delimited string.

This method will take any vector of values and output a list of the values as a comma-delimited string.

Template Parameters
TThe data type held by the vector.
Parameters
valuesThe vector of values to be converted to a string.
Returns
a comma-delimited string representation of the intput values.

◆ ofToString() [2/5]

template<class T >
std::string ofToString ( const T &  value)

Convert a value to a string.

Manipulation

ofToString does its best to convert any value to a string. If the data type implements a stream << operator, then it will be converted.

Example:

std::string str = "framerate is ";
str += ofToString(ofGetFrameRate()) + " fps";
// The string now contains something like "framerate is 60 fps".
float ofGetFrameRate()
Definition ofEvents.cpp:20
std::string ofToString(const T &)
Convert a value to a string.
Definition ofUtils.h:657
Template Parameters
TThe data type of the value to convert to a string.
Parameters
valueThe value to convert to a string.
Returns
A string representing the value or an empty string on failure.

◆ ofToString() [3/5]

template<class T >
std::string ofToString ( const T &  value,
int  precision 
)

Convert a value to a string with a specific precision.

Like sprintf "%4f" format, in this example precision=4

Template Parameters
TThe data type of the value to convert to a string.
Parameters
valueThe value to convert to a string.
precisionThe precision to use when converting to a string.
Returns
The string representation of the value.

◆ ofToString() [4/5]

template<class T >
std::string ofToString ( const T &  value,
int  precision,
int  width,
char  fill 
)

Convert a value to a string with a specific precision, width and filll.

Like sprintf "%04.2d" or "%04.2f" format, in this example precision=2, width=4, fill='0'

Template Parameters
TThe data type of the value to convert to a string.
Parameters
valueThe value to convert to a string.
precisionThe precision to use when converting to a string.
widthThe width of the value to use when converting to a string.
fillThe character to use when padding the converted string.
Returns
The string representation of the value.

◆ ofToString() [5/5]

template<class T >
std::string ofToString ( const T &  value,
int  width,
char  fill 
)

Convert a value to a string with a specific width and fill.

Like sprintf "% 4d" or "% 4f" format, in this example width=4, fill=' '

Template Parameters
TThe data type of the value to convert to a string.
Parameters
valueThe value to convert to a string.
widthThe width of the value to use when converting to a string.
fillThe character to use when padding the converted string.
Returns
The string representation of the value.

◆ ofToUpper()

std::string ofToUpper ( const std::string &  src,
const std::string &  locale = "" 
)

Converts all characters in the string to uppercase.

This function expects a UTF-8 encoded multi-byte string to be passed. Resulting strings will be returned as UTF-8 encoded multi-byte strings.

std::string politeGreeting = "Hello, World!";
std::string enthusiasticGreeting = ofToUpper(politeGreeting);
ofLog() << enthusiasticGreeting; // Returns "HELLO, WORLD!"
string ofToUpper(const string &src, const string &locale)
Definition ofUtils.cpp:797
Parameters
srcThe UTF-8 encoded string to convert to uppercase.
Returns
the UTF-8 encoded string as all uppercase characters.

◆ ofTrim()

std::string ofTrim ( const std::string &  src,
const std::string &  locale = "" 
)

Remove locale-defined whitespace from the beginning and end of a string.

With the default locale, the following white spaces will be removed:

space (0x20, ' ') form feed (0x0c, '\f') line feed (0x0a, '
') carriage return (0x0d, '\r') horizontal tab (0x09, '\t') vertical tab (0x0b, '\v')

std::string original = " Hello, World! ";
std::string trimmed = ofTrim(original);
ofLog() << trimmed; // Returns "Hello, World"
string ofTrim(const string &src, const string &locale)
Definition ofUtils.cpp:826
See also
https://en.cppreference.com/w/cpp/string/byte/isspace
Parameters
srcThe original un-trimmed string.
localeThe locale for determining the definition of "spaces".
Returns
a front-trimmed std::string.

◆ ofTrimBack()

std::string ofTrimBack ( const std::string &  src,
const std::string &  locale = "" 
)

Remove locale-defined whitespace from the end of a string.

With the default locale, the following white spaces will be removed:

space (0x20, ' ') form feed (0x0c, '\f') line feed (0x0a, '
') carriage return (0x0d, '\r') horizontal tab (0x09, '\t') vertical tab (0x0b, '\v')

std::string original = "Hello, World! ";
std::string trimmed = ofTrimBack(original);
ofLog() << trimmed; // Returns "Hello, World"
string ofTrimBack(const string &src, const string &locale)
Definition ofUtils.cpp:818
See also
https://en.cppreference.com/w/cpp/string/byte/isspace
Parameters
srcThe original un-trimmed string.
localeThe locale for determining the definition of "spaces".
Returns
a front-trimmed std::string.

◆ ofTrimFront()

std::string ofTrimFront ( const std::string &  src,
const std::string &  locale = "" 
)

Remove locale-defined whitespace from the beginning of a string.

With the default locale, the following white spaces will be removed:

space (0x20, ' ') form feed (0x0c, '\f') line feed (0x0a, '
') carriage return (0x0d, '\r') horizontal tab (0x09, '\t') vertical tab (0x0b, '\v')

std::string original = " Hello, World!";
std::string trimmed = ofTrimFront(original);
ofLog() << trimmed; // Returns "Hello, World"
string ofTrimFront(const string &src, const string &locale)
Definition ofUtils.cpp:810
See also
https://en.cppreference.com/w/cpp/string/byte/isspace
Parameters
srcThe original un-trimmed string.
localeThe locale for determining the definition of "spaces".
Returns
a front-trimmed std::string.

◆ ofUTF8Append()

void ofUTF8Append ( std::string &  utf8,
uint32_t  codepoint 
)

Append a Unicode codepoint to a UTF8-encoded std::string.

uint32_t original = 0x0001F603; // "πŸ˜ƒ"
std::string utf8String = "Hello ";
ofUTF8Append(utf8String, original);
ofLog() << utf8String; // Prints "Hello πŸ˜ƒ".
void ofUTF8Append(string &str, uint32_t utf8)
Definition ofUtils.cpp:838
Parameters
utf8The UTF8-encoded std::string to be modified.
codepointThe Unicode codepoint that will be converted to UTF8 and appended to utf8.

◆ ofUTF8Erase()

void ofUTF8Erase ( std::string &  utf8,
size_t  pos,
size_t  len 
)

Erase a range of codepoints from a UTF8-encoded substring.

std::string utf8String = "Hello world! πŸ˜ƒ";
ofUTF8Erase(utf8String, 0, 13); // Erase "Hello world! "
ofLog() << utf8String; // Prints "πŸ˜ƒ".
void ofUTF8Erase(string &str, size_t start, size_t len)
Definition ofUtils.cpp:862
Parameters
utf8The string to extract from.
posThe codepoint position in the UTF8-encoded string.
lenThe number of codepoints starting at \pos to extract.
Returns
a UTF8-encoded substring.

◆ ofUTF8Insert()

void ofUTF8Insert ( std::string &  utf8,
size_t  pos,
uint32_t  codepoint 
)

Insert a Unicode codepoint into a UTF8-encoded string at a position.

std::string utf8String = "Helloworld!";
uint32_t codepoint = 0x0001F603; // "πŸ˜ƒ"
ofUTF8Insert(utf8String, 5, codepoint); // Insert "HelloπŸ˜ƒworld!"
ofLog() << utf8String; // Prints "HelloπŸ˜ƒworld!".
void ofUTF8Insert(string &str, size_t pos, uint32_t utf8)
Definition ofUtils.cpp:845
Parameters
utf8The string to insert a codepoint into.
posThe codepoint position in the UTF8-encoded string.
codepointThe codepoint to insert.

◆ ofUTF8Length()

size_t ofUTF8Length ( const std::string &  utf8)

Get the number of Unicode code points in a UTF8-encoded string.

std::string original = "πŸ˜ƒ";
ofLog() << original.size(); // Returns 4.
ofLog() << ofUTF8Length(original); // Returns 1.
size_t ofUTF8Length(const std::string &str)
Get the number of Unicode code points in a UTF8-encoded string.
Definition ofUtils.cpp:898
Parameters
utf8The UTF8-encoded std::string.
Returns
the number of Unicode codepoints in the given string, or 0 if the string is an invalid UTF8 string.

◆ ofUTF8Substring()

std::string ofUTF8Substring ( const std::string &  utf8,
size_t  pos,
size_t  len 
)

Extract a range of codepoints from as a std::string.

std::string utf8String = "Hello world! πŸ˜ƒ";
ofLog() << ofUTF8Substring(utf8String, 13, 1); // Prints "πŸ˜ƒ".
std::string ofUTF8Substring(const string &str, size_t start, size_t len)
Definition ofUtils.cpp:875
Parameters
utf8The string to extract from.
posThe codepoint position in the UTF8-encoded string.
lenThe number of codepoints starting at \pos to extract.
Returns
a UTF8-encoded substring.

◆ ofUTF8ToString()

std::string ofUTF8ToString ( uint32_t  codepoint)

Convert a Unicode codepoint to a UTF8-encoded std::string.

uint32_t original = 0x0001F603; // "πŸ˜ƒ"
std::string utf8String = ofUTF8ToString(original);
ofLog() << utf8String; // Prints πŸ˜ƒ.
std::string ofUTF8ToString(uint32_t utf8)
Convert a Unicode codepoint to a UTF8-encoded std::string.
Definition ofUtils.cpp:891
Parameters
codepointThe Unicode codepoint.
Returns
a UTF8-encoded string.

◆ ofVAArgsToString()

template<typename ... Args>
std::string ofVAArgsToString ( const char *  format,
Args &&...  args 
)

Convert a variable length argument to a string.

Parameters
formatA printf-style format string.
argsA variable argument list.
Returns
A string representation of the argument list.