I'm trying to write simple function trim space in the string in ansi C.
My str_utis.h:
#include <string.h>
const char* trim_str(char *input_str);
My str_utils.c:
const char* trim_str(char* input_str){
char* str = NULL;
int len = strlen(input_str);
int i = 0;
for (i = 0; i < len - 1; i++){
if (input_str[i] == ' ')
;
else
str += input_str[i];
}
return str;
}
When i try to execute it i got segfault:
int main(int argc, char** argv) {
const char* a = trim_str("Hey this is string");
printf("%s", a);
return 0;
}
why is it wrong? how can i write it correctly?
Thank you.
You cannot modify a string literal. It's UB. Copy the string out and modify its contents. Change
char* str = NULL;
int len = strlen(input_str);
to
size_t len = strlen( input_str );
char *str = malloc( len + 1 );
and then proceed to copy out the non-whitespace contents.
str isn't allocated, and you can't use += to append to a string anyway. Read up on strncat.
Go through this. this will remove blank spaces and tabs from both ends of the input string.
const char* trim_str(char* input_str){
char* str = NULL;
int len = strlen(input_str);
str = (char *)malloc(len+1);
int i = 0;
while(i < len && (input_str[i]==' ' || input_str[i]=='\t')){
++i;
}
int j = 0;
while(i< len && input_str[i]!=' ' && input_str[i]!='\t'){
str[j]= input_str[i];
++j;
++i;
}
str[j] = '\0';
return str;
}
first of all you need to get the new string size without spaces: You don't want to allocate big strings if you don't have to.
const char* trim_str(char* input_str){
char* str = NULL;
int len = strlen(input_str);
int i = 0;
int newSize = 0;
for (i = 0; i < len - 1; i++){
if (input_str[i] == ' ')
;
else
newSize++;
}
str = malloc( newSize+ 1 );
str[newSize] = '\0'
// put the code of the copy bytes here...
return str;
}
char *trimdupstr(char *str)
{
size_t len, src,dst;
char *new;
if (!str) return NULL;
len = strlen (str);
new = malloc(len+1);
if (!new) return NULL;
for(src=dst=0; new[dst] = str[src++]; ) {
if (new[dst] != ' ') dst++;
}
return new;
}
And this one also removes tabs and CR/LF's:
char *trimdupstr(char *str)
{
size_t len, src,dst;
char *new;
if (!str) return NULL;
len = strlen (str);
new = malloc(len+1);
for (src=dst=0; str[src]; dst += len) {
len = strspn(str+src, "\t \r\n" );
src += len;
len = strcspn(str+src, "\t \r\n" );
memcpy (new+dst, str+src, len);
src += len;
}
new[dst] = 0;
return new;
}
This is a pretty safe method.
void rtrim(char instrng[]) {
assert (instrng != NULL);
if (strlen(instrng) == 0) {
return;
}
while (instrng[strlen(instrng)-1] == '\n' || instrng[strlen(instrng)-1] == ' ' ) {
instrng[strlen(instrng)-1] = '\0';
}
return;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.