What are strings?

closed account (LN3RX9L8)
I have learned about arrays and now I am leaning about strings what are they and can come one give an example
DO you mean c-strings — or null-terminated strings — (which are arrays of char) or std::string (which are safe, powerful wrapper around c-strings)?
closed account (LN3RX9L8)
Can you explain them all since I'm not sure which one i need to know specifically
c-string is an array of chars which contains characters of string and terminates with 0"
char str[8] = "Hello";Internally it will be:
1
2
3
4
 0   1   2   3   4    5   6   7
'H' 'e' 'l' 'l' 'o' '\0' '█' '█'
                          ^   ^
                         Garbage. 

When we need to iterate over string we usually use for loop wuth condition "until current character is not zero":
1
2
for(int i = 0; str[i] != '\0'; ++i)
    //Do something with str[i] 

Or using the fact that 0 is false:
1
2
for(int i = 0; str[i]; ++i)
    //Do something with str[i] 

Or with pointers:
1
2
3
4
5
6
7
void do_something(char* str)
{
    while(*str){
        //do something
        ++str;
    }
}


You cannot use assigment operator (aside from initialization) or others with c-strings, so you should use specific functions declared in <cstring>:
strncpy() to copy one string to another,
strncat() to contacenate twostrings,
strlen() to know string length...

Main error of many beginners is that they forget about trailing zero:
char x[5] = "Hello";//Error: Hello has 5 characters and another one needed for terminating zero!
Or forger to place it after string manipulation:
str[strlen(str)] = 'x';//Add 'x' at the end of line, overwriting zero character
More correct way:
1
2
3
int x = strlen(str);
str[x] = 'x';
str[x+1] = '\0';

However I did not do bounds cheching anywhere! It can lead to disasterous results.
You should account this too!

std::string is a class which wraps c-strings, so it becomes dynamically sized, safe and supports assigment by '=' operator, operator + to contacenate strings, and others...
MiiNiPaa wrote:
std::string is a class which wraps c-strings

I think that is an over-simplification. Certainly it is possible to convert between one and the other, the behaviour and capabilities are different.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <string>
#include <cstring>

    using namespace std;

int main()
{
    string one = "Rainbow";
    char two[] = "Rainbow";
    
    cout << "one: " << one << endl;
    cout << "two: " << two << endl;
    
    cout << "\nModify both strings\n\n";

    one[4] = '\0';
    two[4] = '\0';    

    cout << "one: " << one << endl;
    cout << "two: " << two << endl;
    
    cout << "Length of one: " << one.size() << endl;
    cout << "Length of two: " << strlen(two) << endl;

    return 0;
}
one: Rainbow
two: Rainbow

Modify both strings

one: Rain ow
two: Rain
Length of one: 7
Length of two: 4

Last edited on
Topic archived. No new replies allowed.