String Dev C++ Example

String Dev C++ Example Average ratng: 3,7/5 6288 votes
  1. String Dev C++ Examples
  2. C# String Methods With Examples
  3. String Dev C++
  4. C++ String Class Example
-->

Controls conditional branching. Statements in the if-block are executed only if the if-expression evaluates to a non-zero value (or TRUE). If the value of expression is nonzero, statement1 and any other statements in the block are executed and the else-block, if present, is skipped. If the value of expression is zero, then the if-block is skipped and the else-block, if present, is executed. Expressions that evaluate to non-zero are

  • TRUE
  • a non-null pointer,
  • any non-zero arithmetic value, or
  • a class type that defines an unambiguous conversion to an arithmetic, boolean or pointer type. (For information about conversions, see Standard Conversions.)

Syntax

Example

if statement with an initializer

If you're already working with streams, for example reading or writing a file, then your second method is the best. If you need to pass an int as a string to a function argument, then itoa could be an easy way. But most of the time, int to string conversion occurs when dealing with files, so streams are appropriate. String variables are declared by using the string type, however as strings aren't actually 'primitive' types in C (and are instead defined by the standard library of stuff that comes bundled with C), you are required to #include string to use this data-type. An example of string declaration and initialization to a string constant is as follows. C programs with output showing usage of operators, loops, functions, arrays, performing operations on strings, files, pointers. Download executable files and execute them without compiling the source file. Code::Blocks IDE is used to write programs, most of these will work with GCC and Dev C compilers. The first program, prints 'Hello World.'

Visual Studio 2017 version 15.3 and later (available with /std:c++17): An if statement may also contain an expression that declares and initializes a named variable. Use this form of the if-statement when the variable is only needed within the scope of the if-block.

Example

C Programs and Examples C Samples Learn Advanced C Programming: Discover intermediate to advanced C, including C 11’s fantastic additions to the C standard. While learning any programming language, practicing the language with examples will. May 15, 2011  Buckys C Programming Tutorials - 71 - string Class and string Functions. Lecture 40 string class in C Part 1 Hindi - Duration. Class Templates in C with Program Example. /traktor-pro-2-free-download-windows.html. File with metadata about the project (.dev), a file with C source code (.c), a file with object code (.o), and a file with linking instructions (makefile.win). Only the.c file must be explicitly created –the remaining files are automatically created by Dev-C. When creating a project, Dev-C asks the user where the files must be stored.

In all forms of the if statement, expression, which can have any value except a structure, is evaluated, including all side effects. Control passes from the if statement to the next statement in the program unless one of the statements contains a break, continue, or goto.

The else clause of an if..else statement is associated with the closest previous if statement in the same scope that does not have a corresponding else statement.

if constexpr statements

Visual Studio 2017 version 15.3 and later (available with /std:c++17): In function templates, you can use an if constexpr statement to make compile-time branching decisions without having to resort to multiple function overloads. For example, you can write a single function that handles parameter unpacking (no zero-parameter overload is needed):

See also

Selection Statements
Keywords
switch Statement (C++)

Simple example of a program using string class and comparison with C char:

C++ String Class:C character:
Compile:
g++ stringtest.cpp -o stringtest
Run: ./stringtest
Results for both examples:

The C and C++ methods of managing a character data type are both valid but we will see that the C++ string class offers more functionality and convenience.The STL string does not require memory to be pre-allocated nor allocated manually.The STL string class also provides many methods of string assignment.

String class functions:
  • Constructors:
  • Destructor:
  • Replace:
    • Var.replace(beginning,end-position,string-class-variable)
    • Var.replace(beginning,end-position,C-char-variable)
    • Var.replace(beginning,end-position,string-class-variable,length)
    • Var.replace(beginning,end-position,integer-number,single-char)
    • Var.replace(beginning,end-position,new-beginning-porition,new-end-position)

    Code samples:

    Output:
    abc ijkbc abd abc - Beginning with the 4th index (character number 5) replace one character with 3 characters from string 'ijk'
    abc ijkd abc
    abc ijk abd abc
    abc abc abd xyzbc
  • Find: (also rfind(), find_first_of(), find_last_of(), find_first_not_of(), find_last_not_of())

    Arguments/parameters:

    • Val.find(const string& argument)
      Find first occurence of argument within string Val
    • find(const string& argument, size_type index)
      Find first occurence of argument within string Val starting search from position index.
    • find(const char* argument)
    • find(const char* argument, size_type index)
    • find(const char* argument, size_type index, size_type length)
      Find first occurence of argument within string Val starting search from position index and search for length number of characters.

STL C++ string functions:

Assuming declaration: string Var;
Function/OperationDescription
Var = string2
Var.assign('string-to-assign')
Assignment of value to string (operator=). When assigning a C 'char' data type, first check if NULL to avoid failure/crash.
i.e.: if( szVar ) sVar.assign( szVar );
where szVar is a C 'char *' data type and sVar is of type 'string'.
Var.swap(string2)
swap(string1,string2)
Swap with value held in string2.
Function swap will exchange contents of two string class variables.
Var += string2
Var.append()
Var.push_back()
Append string/characters to the end of the string.
For string Var('abc'); the call to Var.append('xyz') will result in the string 'abcxyz'.
Var.insert(size_t position, string)
Var.insert(size_t position, char *)
Var.insert(size_t position, string, size_t pos1, size_t len)
Var.insert(size_t position, char *, size_t pos1, size_t len)
Insert characters.
position: insert before this character position. If 0 then insert before the string
pos1: position of the first char of the string being inserted
len: length of string to be inserted
Var.erase()
Var = '
Clear string variable. No arguments necessary.
+Concatenate
, !=, <, <=, >, >=Compare strings.
Var.compare(string)
Var.compare( size_t pos1, size_t len, string ) const;
Var.compare( size_t pos1, size_t len1, const string, size_t pos2, size_t len2 ) const;
Compare strings. Returns int:
  • 0: if equal.
  • -1: Not equal. 1st non matching character in Var is less in value based on ASCII table than in compare string.
  • +1: Not equal. 1st non matching character is greater in value based on ASCII table.
Where string is another STL string or null terminated C string.
Var.length()Return memory allocated to storage of the string. No arguments necessary. The methods length(), size() and capacity() all return the same value.
Var.size()Return length of string. No arguments necessary.
Var.capacity()Return length of string + 1. Red Hat 7.x. Red Hat8.0+ returns the number of characters without the '+1'. Number ofcharacters that can be held without re-allocation.
No arguments necessary.
Var.max_size()Returns a very large number. No arguments necessary.
Var.empty()Returns 1 if an empty string.
Returns 0 if not empty.
<<Output stream
>>
getline()
Input stream
Var.c_str()Returns C string pointer. C char string is null terminated. Do not free memory using this pointer!
Var.data()Returns C string pointer. C char string is NOT null terminated. Do not free memory using this pointer!
Var[]
Var.at(integer)
Access individual characters. Return single character at specified position (integer).
For Var('abc');, Var[2] returns 'c'.
Var.copy(char *str,size_t len, size_t index)str: allocated char storage to which the copy ismade
len: the number of characters to copy
index: the starting place in the string from which to start the copy. Counting starts from 0
returns the number of characters copied
Var.find(string)
Var.find(string, positionFirstChar)
Var.find(string, positionFirstChar, len)
Find first occurance of string or substring. Returns int position of first occurance in string. Where len is the length of the sequence to search for.
Returns string::npos if not found.
i.e. if(Var.find('abc') string::npos) cout << 'Not found' << endl;
Var.rfind()Find last occurance of string or substring.
Var.find_first_of(string, size_t position)
Var.find_first_of( char *str, size_t position)
Var.find_first_of( char *str, size_t position, size_t len )
Find strings and substrings.
Where string is another STL string and str is a null terminated C string.
If position = 0, than start at beginning of string.
Var.find_last_of(string, size_t position)
Var.find_last_of( char *str, size_t position)
Var.find_last_of( char *str, size_t position, size_t len )
Find strings and substrings.
position: the last character considered. If equal to the string length, then the entire string is searched
len: number of characters you are searching for
Var.find_first_not_of()
Var.find_last_not_of()
Find strings and substrings.
Var.replace(pos1, len1, string)
Var.replace(itterator1, itterator2, const string)
Var.replace(pos1, len1, string, pos2, len2)
Replace section of string with new characters.
pos2 and len2 are given when using only a substring of string. Where string is another STL string or null terminated C string.
Var.substr(pos, len)Return substring of text given a start position in string object and length.
Var.begin()
Var.end()
Iterators
Var.rbegin()
Var.rend()
Reverse iterators

Note that in most cases the string functions have been overloaded to acceptboth string class arguments and C char variables.

Iterators provide the ability to access the individual characters in a string.

This will print the integer position in the string followed by the letterfor all characters in the alphabet.

Iterator types:

  • string::traits_type
  • string::value_type
  • string::size_type
  • string::difference_type
  • string::reference
  • string::const_reference
  • string::pointer
  • string::const_pointer
  • string::iterator
  • string::const_iterator
  • string::reverse_iterator
  • string::const_reverse_iterator
  • string::npos

The full use of the C standard library is available for use by utilizing the '.c_str' function return of the string class.

Compile and run:

In memory I/O string processing used as a data type conversion.This can also be used to make use of formatting of output in memory.

File: int2string.cpp

Compile and run: [Potential Pitfall]: Returned string value must be used right away without other memory being set as string destructor willfree the memory associated with its contents. It is much safer for the functionto return a char data type or pass the string reference as an argument.

This is used to make use of reading and parsing a string in memory.It will also allow data type conversion from a string to the type read.

File: test.cpp

Compile and run:

The string function std::to_string() is part of the C++ 11 standard and converts integer and floating point values to a string.The g++ compiler will require the compile flag -std=c++11 to support C++ 11.

FunctionDescription
std::string to_string( int value );Returns a string given an integer
std::string to_string( long long value );Returns a string given a long long
std::string to_string( unsigned value );Returns a string given an unsigned
std::string to_string( unsigned long value );Returns a string given an unsigned long
std::string to_string( unsigned long long value );Returns a string given an unsigned long long
std::string to_string( float value );Returns a string given a float
std::string to_string( double value );Returns a string given a double
std::string to_string( long double value );Returns a string given an long double
Example:Compile and run:

Example of a program using many of the build-in functions of the string class:

Compile: g++ program.cpp

[Potential Pitfall]: In Red Hat Linux versions 7.xone could omit the 'using namespace std;' statement. Use of thisstatement is good programming practice and is required in Red Hat 8.0.

[Potential Pitfall]: Red Hat 8.0 requiresthe reference to '#include <iostream>'. Red Hat versions 7.xused '#include <iostream.h>'. (Also fstream, ..)


[Potential Pitfall]: There have been some changes in the behavior of the string class from Red Hat 7.x to Red Hat 8.0:
  • The compare function arguments have changed from X.compare('string',int-1, int-2); to X.compare(int-1, int-2, 'string');
  • The return value of the compare function call h.compare('abc',0,3) in 7.x was 12. In Red Hat 8.0 h.compare(0,3,'abc') it is 0.
  • String capacity function call 'c.capacity()' is 15. The returned value in Red Hat 7.x was 16.

Code Snipets:

  • Read lines from standard input:
  • Read lines from input file:
  • Strip blank characters:
The String Class and Debugging in GDB:
C++

The first thing you will notice when using the C++ string class is that you can't de-reference any of the string class variables directly with GDB, ddd,.. One must create a helper routine (for older versions of gdb) or use string class funtions (newer versions of gdb) to print out the value of the string variable.

Compile program with symbolic code for the debugger: g++ -g testprog.cpp

Start gdb debugger: gdb ./a.out

With newer versions of gdb, one may use built-in string class functions:

Dereference string and wstring using GDB macro functions. See YoLinux.com GDB tutorial on dereferencing STL strings and containers.

Tips:
  • The string class is NOT a native data type, it is an object class and thus can not be handled like the traditional pointer to variable in gdb.
  • One can pass strings by reference (i.e. argument declarations using (string& variable-name )), by value (string variable-name ), and by pointer (string *variable-name ).
  • When using a reference, one may mimic the protection of a variable that passing by value enables by using (const string& variable-name )

String Dev C++ Examples

  • STL: basic_string - SGI STL home

C# String Methods With Examples

Books:

String Dev C++

The C++ Standard Library: A Tutorial Reference
Nicolai M. Josuttis
ISBN #0201379260, Addison Wesley Longman

This book is the only book I have seen which covers string classes as implemented by current Linux distributions. It offers extensive coverage of the C++ string classes as well as fairly complete coverage of the C++ Standard Template Library (STL).


C++ How to Program
by Harvey M. Deitel, Paul J. Deitel
ISBN #0131857576, Prentice Hall

Fifth edition. The first edition of this book (and Professor Sheely at UTA) taught me to program C++. It is complete and covers all the nuances of the C++ language. It also has good code examples. Good for both learning and reference.


C++ String Class Example

Please enable JavaScript to view the comments powered by Disqus.