I am doing a program in C, and currently I'm having problems. I don't know how to remove the last part of the string. For example:
char str[100] = "one => two";
I want to remove => two. Can you help me? Thanks in advance.
If you want to remove the part after a particular char token then use:
char str[100] = "one => two";
char *temp;
temp = strchr(str,'='); //Get the pointer to char token
*temp = '\0'; //Replace token with null char
In C, the string's end is marked with a zero character. Thus, you can remove the end of the string by writing a zero in the correct position:
str[3] = 0;
find the place of the blank right after "one" and replace it with a '\0'
If the first part of your string always ends before the "=" and assuming it will always have the "=", you could do this:
int i = 0;
char newstr [100];
while (str[i] != '='){
i++;
}
strncpy (newstr, str, i); //copy the i first characters from a char [] to a new char []
newstr [i] = 0;
Remember to include string.h to use strncpy
Related
I need a certain part of the string for example I have
folder1/folder2/folder3/folder4
and I don't want folder4 in my new string so it should be like
folder1/folder2/folder3
any help would be appreciated I searched for strtok and strchar but I couldn't figure out how to achieve this
Find the last occurance of / using strrchr() and then replace it with \0.
int main()
{
char string[] = "folder1/folder2/folder3/folder4";
char character = '/';
char* ptr = strrchr(string, character);
*ptr = '\0';
cout<<string;
return 0;
}
The program I am writing needs to remove an ampersand character if it is the last character of a string. For instance, if char* str contains "firefox&", then I need to remove the ampersand so that str contains "firefox". Does anyone know how to do this?
Just set the last char to be '\0':
str[strlen(str)-1] = '\0';
In C, \0 indicates a string ending.
Every string in C ends with '\0'. So you need do this:
int size = strlen(my_str); //Total size of string
my_str[size-1] = '\0';
This way, you remove the last char.
To be on the safe side:
if (str != NULL)
{
const unsigned int length = strlen(str);
if ((length > 0) && (str[length-1] == '&')) str[length-1] = '\0';
}
Just for reference, the standard function strchr does just that. It effectively splits the string on a given set of characters. It works by substituting a character with 0x00
Example shamelessly stolen from: cplusplus.com
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "This is a firefox& string";
char * pch;
printf ("Looking for the '&' character in \"%s\"...\n",str);
pch=strchr(str,'&');
while (pch!=NULL)
{
printf ("found at %d\n",pch-str+1);
pch=strchr(pch+1,'&');
}
return 0;
}
Check the last character and if it is '&', replace it with '\0' (null terminator):
int size = strlen(my_str);
if (str[size - 1] == '&')
str[size - 1] = '\0';
Having char double[] = "1.2345678"; , I have to trim all digits in 4nd place and above after the . in this char * i.e make it to "1.234" .
Find the '.', advance four steps, and put the string terminator there.
Watch out so you don't pass the string terminator yourself, if the number contains less than three digits after the dot.
To help you find the dot, look up the strchr function.
One obvious solution is to replace a character by NUL, like so:
char *foo = strdup("1.2345678"); // FIXME: check return value
foo[5] = '\0';
Note that the exact position might differ, depening on how many digits appear before the '.' character.
Iterate over the string foo, change the state in passed_dot if you come across '.', and insert a NUL after 4 more characters:
char *p = foo;
int i = 0;
int passed_dot = 0;
while (p && *p) {
if (*p == '.') passed_dot = 1;
if (passed_dot) i++;
if (i == 4) {
*p = '\0';
break;
}
p++;
}
If you can't afford to buy more RAM, you may strdup() the resulting string and free() the old one in order to save memory:
new_str = strdup(foo); // and don't forget to check for NULL
free(foo);
Note that
char * double= "1.2345678";
declares a string literal. This is const so can't be directly modified. To get a modifiable string, you could declare it as
char double[] = "1.2345678";
or
char* double = strdup("1.2345678");
then insert a nul character as suggested in other answers.
In C, how do I extract the first n characters from a string until I find a space in the string? Essentially, which C function will find the position of the next space for me and which C function will give me a substring? I am thinking in terms of C++. such as:
string str = "Help me Please!";
int blankPos = str.find(' ');
str.substr(0, blankPos);
Thanks,
Use strchr to find the space.
Allocate a new char buffer to hold the substring.
Copy the substring into the buffer with memcpy.
hint: strchr()
I need to type some more characters.
char str[] = "Help me Please"; // Source string
char newstr[80]; // Result string
// Copy substring characters until you reach ' ' (i.e. "Help")
for (i=0; str[i] != ' '; i++) {
newstr[i] = str[i];
}
newstr[i] = 0; // Add string terminator at the end of substring
If you just want to get the first part of the string, use strchr() as everyone has suggested. If you're looking to break a string into substrings delimited by spaces, then look into strtok().
So you want something like:
#include <string.h>
const char *str = "Help me Please";
//find space charachter or end of string if no space found
char *substr, *space = strchr(str, ' ');
int len = space ? (space-str) : strlen(str);
//create new string and copy data
substr = malloc(len+1);
memcpy(substr, str, len);
substr[len] = 0;
char* str = "Help me Please";
int i =0;
//Find first space
while(str[i] != ' '){
i++;
}
char* newstr;
newstr = strndup(str+0,i);
I guess you could also use strchr() to get the first space in the string.
Another variant allowing to use more than one character as delimitter.
char str[] = "Help me Please";
char newstr[80];
char *p = strpbrk(str, " \t\xA0"); /* space, tab or non-breaking space (assuming western encoding, that part would need adaptation to be trule portable) */
if(p)
strlcpy(newstr, str, p - str + 1);
else
newstr[0] = 0;
strlcpy is not standard but widespread enough to be used. If it is not available on the platform, it's easy to implement. Note that strlcpy always puts a 0 at the last position copied, therfore the +1 in the length expression.
/* strchr example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "This is a sample string";
char * pch;
printf ("Looking for the 's' character in \"%s\"...\n",str);
pch=strchr(str,'s');
while (pch!=NULL)
{
printf ("found at %d\n",pch-str+1);
pch=strchr(pch+1,'s');
}
return 0;
}
How would I index the str so that I would replace every 's' with 'r'.
Thanks.
You don't need to index the string. You have a pointer to the character you want to change, so assign via the pointer:
*pch = 'r';
In general, though, you index using []:
ptrdiff_t idx = pch - str;
assert(str[idx] == 's');
You can use the following function:
char *chngChar (char *str, char oldChar, char newChar) {
char *strPtr = str;
while ((strPtr = strchr (strPtr, oldChar)) != NULL)
*strPtr++ = newChar;
return str;
}
It simply runs through the string looking for the specific character and replaces it with the new character. Each time through (as with yours), it starts with the address one beyond the previous character so as to not recheck characters that have already been checked.
It also returns the address of the string, a trick often used so that you can use the return value as well, such as with:
printf ("%s\n", chngChar (myName, 'p', 'P'));
void reeplachar(char *buff, char old, char neo){
char *ptr;
for(;;){
ptr = strchr(buff, old);
if(ptr==NULL) break;
buff[(int)(ptr-buff)]=neo;
}
return;
}
Usage:
reeplachar(str,'s','r');
Provided that your program does really search the positions without fault (I didn't check), your question would be how do I change the contents of an object to which my pointer pch is already pointing?