C语言 打印字符数组的一部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5189071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:57:41  来源:igfitidea点击:

Print part of char array

c

提问by user461316

So:

所以:

char *someCArray; # something

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

我想从“某物”中打印出“ethin”。

回答by pmg

You can use the printfprecision specifier

您可以使用printf精度说明符

#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

代码也发布到键盘:http: //codepad.org/q5rS81ox

回答by Algorithmist

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

考虑到您只想打印“ ethin”而不是“ 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.

正如@Mahesh 在他的评论中所说,您必须给出要打印字符的开始和结束位置,以使您的程序更通用。

Char *p ="Something";

Char *p ="Something";

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

char *temp=p;//考虑到您可能在某个时间点需要字符串的基地址。

temp=temp+3;

temp=temp+3;

while(*temp!='g')

while(*temp!='g')

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

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.

如果您对您的要求更具体,我们可以进一步帮助您。这些是 C 语言的基础知识,因此您必须彻底研究 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.

我无法给你完整的代码,因为这会违反 Stackoverflow 规则和 moto,就像程序员的“技术库和天堂旁边”。因此我只能给你逻辑。

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.

继续打印字符,直到开始和结束位置相等或它们的差为零。您可以选择上述两种方法中的任何一种。

回答by ducvd

Try

尝试

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

The result will be : "ethin"

结果将是:“ethin”

回答by jnermano

#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

printf 字符串中的“%.Ns”表示法是带有精度说明符的“%s”。检查 printf(3) 手册页