Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointing to a some characters in a string using pointer

#include<iostream>
using namespace std;
int main()
{
    char s1[80]={"This is a developed country."};
    char *s2[8];
    s2[0]=&s1[10];
    cout<<*s2;    //Predicted OUTPUT: developed
                    // Actual OUTPUT: developed country.
    return 0;
}

I want that the cout<<*s2; should print only the letters {"developed"} in it, so I gave *s2[8] length as 8 characters. What can I do so that the variable cout<<*s2 will only print upto the length of 8 characters. I'm using dmc, lcc and OpenWatcom compilers. This is only a small part of other bigger program where I'm using string data type, so what can I do now, well extremely thanks for answering my question :)

like image 213
Tuesday Avatar asked Aug 24 '26 14:08

Tuesday


1 Answers

s2 is a length 8 array of pointers to char. You are making its first element point to s1 starting at position 10. That is all. You are not using the remaining elements of that array. Therefore the length of s2 is irrelevant.

You could have done this instead:

char* s2 = &s1[10];

If you want to create a string out of part of s1, you can use std::string:

std::string s3(s1+10, s1+19);
std::cout << s3 << endl;

Note that this allocates its own memory buffer and holds a copy or the original character sequence. If you only want a view of part of another string, you can easily implement a class holding a begin and one-past the end pointer to the original. Here's a rough sketch:

struct string_view
{
    typedef const char* const_iterator;
    template <typename Iter>
    string_view(Iter begin, Iter end) : begin(begin), end(end) {}

    const_iterator begin;
    const_iterator end;
};

std::ostream& operator<<(std::ostream& o, const string_view& s)
{
    for (string_view::const_iterator i = s.begin; i != s.end; ++i)
      o << *i;
    return o;
}

then

int main()
{
    char s1[] = "This is a developed country.";
    string_view s2(s1+10, s1+19);
    cout << s2 << endl;
}
like image 88
juanchopanza Avatar answered Aug 26 '26 07:08

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!