TomM12
TomM12

Reputation: 55

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?

Upvotes: 1

Views: 362

Answers (3)

maxdev
maxdev

Reputation: 2566

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);
}

Upvotes: 4

Sourav Ghosh
Sourav Ghosh

Reputation: 134336

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.

Upvotes: 3

n0p
n0p

Reputation: 3496

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);

Upvotes: 2

Related Questions