在C字符串的一部分打印 [英] Print part of a string in C

查看:96
本文介绍了在C字符串的一部分打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法为一个字符串的唯一打印一部分?

Is there a way to only print part of a string?

例如,如果我有

char *str = "hello there";

有没有办法只打印你好,牢记我要打印的子串的长度是可变,不总是5个字符?

Is there a way to just print "hello", keeping in mind that the substring I want to print is variable length, not always 5 chars?

我知道,我可以使用循环和的putchar ,或者我可以在阵列复制,然后添加空终止,但我不知道是否有一个更优雅的方式?

I know that I could use a for loop and putchar or that I could copy the array and then add a null-terminator but I'm wondering if there's a more elegant way?

推荐答案

试试这个:

int length = 5;
printf("%*.*s", length, length, "hello there");

这篇关于在C字符串的一部分打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆