13

So:

char *someCArray; # something

I want to print out "ethin" from "something".

1
  • You should give the input of position1 and position2 to print the characters in between. Or the question would have been whether "ethin" is part of "something" and print if it is. Commented Mar 4, 2011 at 2:55

4 Answers 4

29

You can use the printf precision specifier

#include <stdio.h>

int main(void) {
  char s[] = "something";
  int start = 3;
  int len = 5;

  printf("%.*s\n", len, s + start);

  return 0;
}

Code also posted to codepad: http://codepad.org/q5rS81ox

Sign up to request clarification or add additional context in comments.

Comments

1

This Would do the Job Considering you want to print only "ethin" not "ething".

As @Mahesh said in his comment you must give the start and end position from where you want to print characters to make your program more general.

Char *p ="Something";

char *temp=p; //Considering you may require at some point on time the base address of your string.

temp=temp+3;

while(*temp!='g')

printf("%c",*temp++);

If you would be more specific about your requirement we can further help you.These are the basics of C language thus you must thoroughly study arrays,pointers in c.

EDIT:

I won't be able to give you the complete code as this would be against the Stackoverflow rules and moto which is like "Technical Repository And Next To Heaven" for programmers.Thus i can only give you the logic.

Keep on printing characters untill both start and end position becomes equal or their difference becomes zero.You can choose any of the above two methods.

2 Comments

Was just looking for a printf format that does this. printf("%.s(length)", &s[startpoint]) works
@user461316 could you please eleborate what you actually want to do.
1
#include <stdio.h>

int main()
{
        char a[1024] = "abcdefghijklmnopqrstuvwxyz";
        printf("Characters 0 through 2 of a[]: %.3s\n", a);
        printf("Characters 10 through 15 of a[]: %.6s\n", &a[10]);
        return 0;
}

Prints this

Characters 0 through 2 of a[]: abc
Characters 10 through 15 of a[]: klmnop

The "%.Ns" notation in the printf string is "%s" with a precision specifier. Check the printf(3) man page

Comments

0

Try

char* strSth = "something"; 
std::string strPart; 
strPart.assign(strSth+3,strSth+8);
std::cout << strPart;

The result will be : "ethin"

1 Comment

He is using the C language, not C++.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.