Thread: Shifiting all elements of a string

  1. #1
    Registered User
    Join Date
    Sep 2016
    Posts
    2

    Shifiting all elements of a string

    Hi,
    I'm trying to shift all elements of a string to the left (so the first letter is cut off) one-by-one until the end of the string
    Code:
    #include <stdio.h>
    #include <string.h>
    int main(){
        char string1[32] = "This is a string", string2[32], string3[32], string4[32];
        int i, j, k;
        
        for(i = 0; i < 32; i++){
         string2[k] = string1[0];
         string1 << 1;
         printf("%c", string2[k]);
        }
    }
    This is what I have so far but I get an error when compiling the program that says this:
    stringmaniptest.c: In function ‘main’:
    stringmaniptest.c:9:14: error: invalid operands to binary << (have ‘char *’ and ‘int’)
    string1 << 1;
    ^
    Would anyone be able to advise me on how to fix this?
    Thanks

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    The simplest way to do this is probably to use a pointer to point to the second element instead of actually shifting, e.g.,
    Code:
    #include <stdio.h>
    
    int main(void)
    {
        char original_string[] = "hello world!";
        char *shifted_string = original_string + 1;
        printf("%s -> %s\n", original_string, shifted_string);
        return 0;
    }
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. delete last 2 elements of a string
    By maxzoran in forum C Programming
    Replies: 15
    Last Post: 08-03-2010, 11:32 AM
  2. replacing string elements
    By Dorothy in forum C Programming
    Replies: 4
    Last Post: 06-17-2010, 09:40 AM
  3. Adding elements to a string
    By Vicked in forum C Programming
    Replies: 2
    Last Post: 04-10-2003, 12:52 PM
  4. Switching string elements
    By Pietro in forum C Programming
    Replies: 0
    Last Post: 04-25-2002, 05:50 AM
  5. reversing the elements of a string
    By lostpoet in forum C Programming
    Replies: 2
    Last Post: 03-08-2002, 08:08 AM

Tags for this Thread