如何解决字符串打印,不包括前N个字符
我想在printf
语句中打印我的字符串,该字符串为没有前N个字母。
示例1 :我可以做“相反”(printf
仅N个首字母):
#include <stdio.h>
int main() {
char str[] = "Something";
printf("%5s",str);
}
输出:Somet
预期输出:hing
解决方法
从中间开始打印:
// needed to read certificates from disk
const fs = require( "fs" );
// Servers with and without SSL
const http = require( "http" )
const https = require( "https" );
const httpPort = 3333;
const httpsPort = 3334;
const httpServer = http.createServer();
const httpsServer = https.createServer({
"key" : fs.readFileSync( "localhost.key" ),"cert": fs.readFileSync( "localhost.crt" ),"requestCert": false,"rejectUnauthorized": false
});
httpServer.listen( httpPort,function() {
console.log( `Listening HTTP on ${httpPort}` );
});
httpsServer.listen( httpsPort,function() {
console.log( `Listening HTTPS on ${httpsPort}` );
});
// Socket.io
const ioServer = require( "socket.io" );
const io = new ioServer();
io.attach( httpServer );
io.attach( httpsServer );
io.on( "connection",function( socket ) {
console.log( "user connected" );
// ... your code
});
,
您可以尝试使用指针算法在要开始打印的字符串中传递起点的地址。在更一般的情况下,您将需要以某种方式检查要跳过的字符数是否小于主字符串的总长度。
#include<stdio.h>
int main()
{
char str[]="Something";
int numCharsToSkip = 5;
printf("%s",(str + numCharsToSkip));
}
,
有许多方法可以选择从缓冲区开始打印的位置。一个可能有用的函数strchr(const char *buf,char ch)返回一个指向char
ch 首次出现的指针。因此,如果您想以字母h
开始打印,请以这种方式调用strchr()
:
对于预期的输出hing
,请使用:
char str[]="Something";
printf("%s",strchr(str,'h');
或者,对于预期的输出omething
,使用:
printf("%s",'o');
另一个有用的函数:strstr(const char *source,const char *search)返回指向 source 缓冲区中存在的任何子字符串 search 的指针,因此如果您想开始在更大的缓冲区中的特定单词上打印,例如:
char longerStr[] = "This is really something else";
char *token = strstr(longerStr,"thing");
if(token) //test before using to prevent trying to print a nul pointer in the event
{ //"thing" is not found in buffer.
printf("%s",token);//note using " ",not ' '
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。