[c] Strings in C, how to get subString

I have a string:

char * someString;

If I want the first five letters of this string and want to set it to otherString, how would I do it?

This question is related to c

The answer is


You can use snprintf to get a substring of a char array with precision. Here is a file example called "substring.c":

#include <stdio.h>

int main()
{
    const char source[] = "This is a string array";
    char dest[17];

    // get first 16 characters using precision
    snprintf(dest, sizeof(dest), "%.16s", source);

    // print substring
    puts(dest);
} // end main

Output:

This is a string

Note:

For further information see printf man page.


Doing it all in two fell swoops:

char *otherString = strncpy((char*)malloc(6), someString);
otherString[5] = 0;

char* someString = "abcdedgh";
char* otherString = 0;

otherString = (char*)malloc(5+1);
memcpy(otherString,someString,5);
otherString[5] = 0;

UPDATE:
Tip: A good way to understand definitions is called the right-left rule (some links at the end):

Start reading from identifier and say aloud => "someString is..."
Now go to right of someString (statement has ended with a semicolon, nothing to say).
Now go left of identifier (* is encountered) => so say "...a pointer to...".
Now go to left of "*" (the keyword char is found) => say "..char".
Done!

So char* someString; => "someString is a pointer to char".

Since a pointer simply points to a certain memory address, it can also be used as the "starting point" for an "array" of characters.

That works with anything .. give it a go:

char* s[2]; //=> s is an array of two pointers to char
char** someThing; //=> someThing is a pointer to a pointer to char.
//Note: We look in the brackets first, and then move outward
char (* s)[2]; //=> s is a pointer to an array of two char

Some links: How to interpret complex C/C++ declarations and How To Read C Declarations


char largeSrt[] = "123456789-123";  // original string

char * substr;
substr = strchr(largeSrt, '-');     // we save the new string "-123"
int substringLength = strlen(largeSrt) - strlen(substr); // 13-4=9 (bigger string size) - (new string size) 

char *newStr = malloc(sizeof(char) * substringLength + 1);// keep memory free to new string
strcpy(newStr, largeSrt, substringLength);  // copy only 9 characters 
newStr[substringLength] = '\0'; // close the new string with final character

printf("newStr=%s\n", newStr);

free(newStr);   // you free the memory 

This code is substr function that mimics function of same name present in other languages, just parse: string, start and number of characters like:

#include <stdio.h>

printf( "SUBSTR: %s", substr("HELLO WORLD!",2,5) );

The above will print HELLO. If you pass a value over the string length, it will be silently ignored, as the loop only iterates the length of the string.

#include <stdlib.h>

char *substr(char *s, int a, int b) {
    char *r = (char*)malloc(b);
    strcpy(r, "");
    int m=0, n=0;
    while(s[n]!='\0')
    {
        if ( n>=a && m<b ){
            r[m] = s[n];
            m++;
        }   
        n++;
    }
    r[m]='\0';
    return r;
}

#include <stdio.h>
#include <string.h>

int main ()
{
        char someString[]="abcdedgh";
        char otherString[]="00000";
        memcpy (otherString, someString, 5);
        printf ("someString: %s\notherString: %s\n", someString, otherString);
        return 0;
}

You will not need stdio.h if you don't use the printf statement and putting constants in all but the smallest programs is bad form and should be avoided.


You can treat C strings like pointers. So when you declare:

char str[10];

str can be used as a pointer. So if you want to copy just a portion of the string you can use:

char str1[24] = "This is a simple string.";
char str2[6];
strncpy(str1 + 10, str2,6);

This will copy 6 characters from the str1 array into str2 starting at the 11th element.


strncpy(otherString, someString, 5);

Don't forget to allocate memory for otherString.


You'll need to allocate memory for the new string otherString. In general for a substring of length n, something like this may work for you (don't forget to do bounds checking...)

char *subString(char *someString, int n) 
{
   char *new = malloc(sizeof(char)*n+1);
   strncpy(new, someString, n);
   new[n] = '\0';
   return new;
}

This will return a substring of the first n characters of someString. Make sure you free the memory when you are done with it using free().


Generalized:

char* subString (const char* input, int offset, int len, char* dest)
{
  int input_len = strlen (input);

  if (offset + len > input_len)
  {
     return NULL;
  }

  strncpy (dest, input + offset, len);
  return dest;
}

char dest[80];
const char* source = "hello world";

if (subString (source, 0, 5, dest))
{
  printf ("%s\n", dest);
}

I think it's easy way... but I don't know how I can pass the result variable directly then I create a local char array as temp and return it.

char* substr(char *buff, uint8_t start,uint8_t len, char* substr)
{
    strncpy(substr, buff+start, len);
    substr[len] = 0;
    return substr;
}