Using sprintf to format printing of char array

I have a char array that contains some string for example

char* arr = "ABCDEFGHIJKL ZMN OPQOSJFS"

and the string

char* string = "ZMN"

Is there any printing method that will print the content of arr only after the first occurrence of string in it? In this case it will print " OPQOSJFS"

What about sprintf, and if so, how do I do that?

Answers


sprintf won't help you here; use strstr to find the occurence and then print the source string from there on:

// note: your string constants should be of type 'const char*'
const char* haystack = "ABCDEFGHIJKL ZMN OPQOSJFS";
const char* needle = "ZMN";

// find occurence of the string
const char* out = strstr(haystack, needle);
if(out != NULL) {
    // print string, starting from the end of the occurence
    out += strlen(needle);
    printf("The string is: %s", out);
}

Firstly, let me tell you,

I have a char array that contains some string for example

char* arr = "ABCDEFGHIJKL ZMN OPQOSJFS"

is wrong. "ABCDEFGHIJKL ZMN OPQOSJFS" is a string literal, and arr is just a pointer, not an array.

If you indeed need arr to be called an array, you need to write it like

 char arr[] = "ABCDEFGHIJKL ZMN OPQOSJFS";

Now, for your requirement, you can have a look at strstr() function, prototyped in string.h header.

Prototype:

char *strstr(const char *haystack, const char *needle);

Description:

The strstr() function finds the first occurrence of the substring needle in the string haystack.

So, if it returns a non-NULL pointer, you can use that value to point out the location of the substring, and using index, you can get the required part of the source string.


strstr will give you a pointer on the substring you are looking for. You can then jump after this string and printf its content.

char * sub = strstr(arr, string);
sub += strlen(string);
printf("%s\n", sub);

Need Your Help

android.util.Pair as key in HashMap

java android

Is it Ok to use http://developer.android.com/reference/android/util/Pair.html this for keys in HashMap?