help with string slicing in C


 
Thread Tools Search this Thread
Top Forums Programming help with string slicing in C
# 1  
Old 04-03-2011
help with string slicing in C

i have a string and i want the first 5 chars to be removed
this is what i have
Code:
void shift(char *string) {
    int i;
    for(i=0;i<5;i++) {
        while(1) {
            *string = *(string+1);
            if (*string=='\0') break;
        }
        
    }
}

its not working, i think it maybe because my string isnt terminated properly, but anyways can you see if this function is right?

---------- Post updated 04-03-11 at 12:06 AM ---------- Previous update was 04-02-11 at 11:17 PM ----------

nvm i got it using
Code:
void shift(char *string) {
    int i, k;
    char *h=string;
    int j=strlen(string);
    for(k=0;k<5;k++) {
        for(i=0;i<j;i++) {
            *string = *(string+1);
            string++;
        }
        string=h;
        j=strlen(string);
    }
}

# 2  
Old 04-03-2011
This is one way of manyto whack off the first n chars of string:
Code:
char *whack(char *src, size_t start)
{
      if(strlen(src) >= start)
      {
          char *p=strdup(src);
          p+=start;
          strcpy(src, p);
          free(p);
      }
      return src;
}

# 3  
Old 04-03-2011
Quote:
Originally Posted by jim mcnamara
This is one way of manyto whack off the first n chars of string:
Code:
char *whack(char *src, size_t start)
{
      if(strlen(src) >= start)
      {
          char *p=strdup(src);
          p+=start;
          strcpy(src, p);
          free(p);  // p has been modified
      }
      return src;
}

Smilie Calling "free(p)" after "p+=start" will corrupt the heap.

My shot:

Code:
char *shift( char *str, size_t count )
{
    size_t len;

    if ( NULL == str )
    {
        return( NULL );
    }

    len = strlen( str );
    if ( len > count )
    {
        return( NULL );
    }

    memmove( str, str + cpunt, len - count + 1 );

    return( str );
}

# 4  
Old 04-04-2011
Fast but no error checking added!
Code:
void
shift(char *string)
{
    char *ptr = string;

    while (*(ptr+5)) {
       *ptr = *(ptr+5);
       ptr++;
    }
    *ptr = '\0';
}

# 5  
Old 04-04-2011
The dumb+easy way is to use pointer math:

Code:
const char *str="0123456789";

printf("Entire string is %s\n", str);
printf("With 5 lopped off the front:  %s\n", str+5);

Superfast, too. Smilie One instruction beats copying an entire string.
# 6  
Old 04-05-2011
Bug

Quote:
Originally Posted by achenle
Smilie Calling "free(p)" after "p+=start" will corrupt the heap.

My shot:

Code:
char *shift( char *str, size_t count )
{
    size_t len;

    if ( NULL == str )
    {
        return( NULL );
    }

    len = strlen( str );
    if ( len > count )
    {
        return( NULL );
    }

    memmove( str, str + cpunt, len - count + 1 );

    return( str );
}

should be
Code:
 if (count > len)

Thanks,
Gaurav.

---------- Post updated at 03:08 PM ---------- Previous update was at 02:57 PM ----------
Another way ,

Code:
 void * shiftbyn( char *str, size_t count )
{
    size_t len = 0;
    char *newstr = NULL;

    if ( NULL == str )
    {
        return NULL;
    }

    len = strlen( str );
    if ( count > len )
    {
        return NULL;
    }

    newstr = malloc (strlen(str) - count);
    strcpy (newstr, str + count);
    free (str); str = NULL;
    return newstr;
}

Thanks,
Gaurav.
# 7  
Old 04-06-2011
wouldnt this work, since strings are pointers?
buf=buf+5;

and whats the difference between declaring a string like
char *buf;
and
char buf[10];

arent they both pointers? But in some cases the way i declare it makes a difference through...
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. UNIX for Beginners Questions & Answers

awk Associative Array and/or Referring to Field by String (Nonconstant String Value)

I will start with an example of what I'm trying to do and then describe how I am approaching the issue. File PS028,005 Lexeme HRS # M # PhraseType 1(1:1) 7(7) PhraseLab 501 503 ClauseType ZYq0 PS028,005 Lexeme W # L> # BNH # M #... (17 Replies)
Discussion started by: jvoot
17 Replies

2. UNIX for Beginners Questions & Answers

Search a string and display its location on the entire string and make a text file

I want to search a small string in a large string and find the locations of the string. For this I used grep "string" -ob <file name where the large string is stored>. Now this gives me the locations of that string. Now how do I store these locations in a text file. Please use CODE tags as... (7 Replies)
Discussion started by: ANKIT ROY
7 Replies

3. Shell Programming and Scripting

awk string comparison unterminated quoted string andrule of thumb

I have the logic below to look up for matches within the columns between the two files with awk. In the if statement is where the string comparison is attempted with == The issue seems to be with the operands, as 1. when " '${SECTOR}' " -- double quote followed by single quote -- awk matches... (1 Reply)
Discussion started by: deadyetagain
1 Replies

4. Shell Programming and Scripting

Insert String every n lines, resetting line counter at desired string

I need to read a text file and insert a string every n lines, but also have the line counter restart when I come across a header string. Line repeating working every 3 lines using code: sed '0~3 s/$/\nINSERT/g' < INPUT/PATH/FILE_NAME.txt > OUTPUT/PATH/FILE_NAME.txt I cannot seem to find... (1 Reply)
Discussion started by: Skonectthedots
1 Replies

5. Shell Programming and Scripting

Bash script with python slicing on multiple data files

I have 2 files generated in linux that has common output and were produced across multiple hosts with the same setup/configs. These files do some simple reporting on resource allocation and user sessions. So, essentially, say, 10 hosts, with the same (2) system reporting in the files, so a... (0 Replies)
Discussion started by: jdubbz
0 Replies

6. Shell Programming and Scripting

Remove lines between the start string and end string including start and end string Python

Hi, I am trying to remove lines once a string is found till another string is found including the start string and end string. I want to basically grab all the lines starting with color (closing bracket). PS: The line after the closing bracket for color could be anything (currently 'more').... (1 Reply)
Discussion started by: Dabheeruz
1 Replies

7. Shell Programming and Scripting

grep exact string from files and write to filename when string present in file

I am attempting to grep an exact string from a series of files within a directory and append that output to the filename when it is present in the file. I've been after this all day with no luck. Thanks for your help in advance :wall:. (4 Replies)
Discussion started by: JC_1
4 Replies

8. Shell Programming and Scripting

sed or awk command to replace a string pattern with another string based on position of this string

here is what i want to achieve... consider a file contains below contents. the file size is large about 60mb cat dump.sql INSERT INTO `table1` (`id`, `action`, `date`, `descrip`, `lastModified`) VALUES (1,'Change','2011-05-05 00:00:00','Account Updated','2012-02-10... (10 Replies)
Discussion started by: vivek d r
10 Replies

9. Shell Programming and Scripting

to extract string from main string and string comparison

continuing from my previous post, whose link is given below as a reference https://www.unix.com/shell-programming-scripting/171076-shell-scripting.html#post302573569 consider there is create table commands in a file for eg: CREATE TABLE `Blahblahblah` ( `id` int(11) NOT NULL... (2 Replies)
Discussion started by: vivek d r
2 Replies

10. Shell Programming and Scripting

replace (sed?) a string in file with multiple lines (string) from variable

Can someone tell me how I can do this? e.g: a=$(echo -e wert trewt ertert ertert ertert erttert erterte rterter tertertert ert) How do i replace the STRING with $a? I try this: sed -i 's/STRING/'"$a"'/g' filename.ext but this don' t work (2 Replies)
Discussion started by: jforce
2 Replies
Login or Register to Ask a Question