-
January 24th, 2011, 07:08 AM
#1
handle character at string(c)
hi,
i wanted to know if there is any way to read character`s from string one by one,
and set it in other string.
i mean
i have this string:
char *get = "hello";
now i want to get over the string char by char and if the letter != 'l' copy it to other string, like :
Code:
char *copy;
char c; int i;
for (i=0;get[i] != '\0';i++)
c = get[i];
if (c != 'l')
{
copy[j] = get[i];
j++;
}
i dont want to do it by strchr,strtok... i want do it by reading char by char from the string,
(the all problem when i tring to add the char to the copy array it tells me :
canot covert char to char *
any idea?
Thanks,
Or.
-
January 24th, 2011, 07:29 AM
#2
Re: handle character at string(c)
Is the code you posted really the code you got that error message for? I don't see what statement in that code could trigger that error.
I do see several problems in that short snippet though:
- You would need to allocate memory to hold the output characters and assign its address to copy. Since you don't know in advance how many characters will be skipped I would suggest to allocate strlen(get)+1 chars.
- You are missing a pair of braces. The way it is the for loop would only comprise the single statement following the for line.
- You are neither declaring nor initializing j.
- You don't copy the '\0' terminator at the end of the string.
I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.
This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.
-
January 24th, 2011, 07:44 AM
#3
Re: handle character at string(c)
This pseudo-code is the sort of thing that would do the job. It should explain to you a method.
Code:
// Get length of source char array (using strlen).
// Make target char array of this size (plus one for the terminating zero) using new.
int positionInTargetArray = 0;
for (int i=0;i==lengthOfSourceCharArray;++i) // For each character in the source char array and the terminating zero....
{
if (sourceCharArray[i] != 'l') // Check if it should be copied...
{
targetArray[positionInTargetArray]=sourceCharArray[i]; // Copy it to the next available slot
// in the target array
++positionInTargetArray; // Move the target array next slot counter along one.
}
}
// Be sure that you don't miss the terminating zero at the end of the char arrays.
-
January 24th, 2011, 08:00 AM
#4
Re: handle character at string(c)
I don't know what would cause that error, but you'll need to allocate memory for copy.
-
January 24th, 2011, 10:23 AM
#5
Re: handle character at string(c)
Code:
string get = "somethingblue";
string copy;
for (unsigned i = 0; i < get.size(); ++i)
if (get[i] != 'l')
copy += get[i];
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|