Sign in to follow this  

I have a problem with char*

This topic is 2551 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi,
I have a problem with char*.

1)Please tell me why this code is wrong?

#include <iostream>
using namespace std;

void main()
{
char* s = "hello";
s[1] = 'n';
cout << s;
}
2)How can I change an index of my char*?
(In fact I want to delete some part of my char* for example I want to change "FirstName:Jack" to "Jack")

for now!

Share this post


Link to post
Share on other sites
<insert usual disclaimer about using std::string rather than char*>

1) your code is wrong because you make s point to a constant literal string which can not be modified (s should have type const char* in your example)
If you want to initialize a char array from a literal, use:

char s[] = "hello";


You can then modify that array.

2) there are many ways to do that. unless you use std::string instead (which offers high level string manipulation functions), it boils down to manual array manipulation.

An *example* (I encourage you to use std::string instead)


char s[] = "FirstName:Jack";
for (int i = 0 ; i < 5 ; i++)
s[i] = s[i+10]; // because 'J' is at index 10

Share this post


Link to post
Share on other sites
Since the previous poster provided actual helpful relevant posts, heres my help:

It's wrong because it uses char*. Since you are obviously using C++, char* is basically considered evil as a string. Use std::string instead.

Share this post


Link to post
Share on other sites
Q2)

You can create suffix substrings using pointer arithmethic:

#include <iostream>
#include <algorithm>

int main()
{
const char *string = "FirstName:Jack";
std::cout << "Full string: " << string << '\n';
const char *end = string + std::strlen(string);
const char *substring = std::find(string, end, ':');

if(substring == end)
{
std::cout << "Failed to find \':\' in string\n";
}
else
{
std::cout << "Sub string: " << (substring + 1) << '\n';
}
}


But to echo Steve132, std::string is almost always a superior solution.

Share this post


Link to post
Share on other sites

This topic is 2551 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this