![](/img/trans.png)
[英]Printing hex integer by casting to char* and using “%s” in sprintf
[英]Using sprintf to format printing of char array
我有一個包含一些字符串的char數組,例如
char* arr = "ABCDEFGHIJKL ZMN OPQOSJFS"
和字符串
char* string = "ZMN"
是否有任何打印方法僅在第一次出現字符串后才打印arr的內容? 在這種情況下,它將打印" OPQOSJFS"
sprintf
怎么樣?如果是,我該怎么做?
sprintf
不會在這里幫助您; 使用strstr
查找出現的內容,然后從那里打印源字符串:
// 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);
}
首先,我告訴你,
我有一個包含一些字符串的char數組,例如
char* arr = "ABCDEFGHIJKL ZMN OPQOSJFS"
是錯的。 "ABCDEFGHIJKL ZMN OPQOSJFS"
是字符串文字,而arr
只是一個指針,而不是數組。
如果確實需要將arr
稱為數組 ,則需要像這樣編寫它
char arr[] = "ABCDEFGHIJKL ZMN OPQOSJFS";
現在,根據您的要求,您可以看看strstr()
函數,該函數原型為string.h
標頭。
原型:
char *strstr(const char *haystack, const char *needle);
描述:
strstr()
函數查找字符串haystack
字符串needle
的首次出現。
因此,如果它返回一個非NULL指針,則可以使用該值指出子字符串的位置,並使用索引可以獲取源字符串的必需部分。
strstr
將為您提供您要查找的子字符串的指針。 然后,您可以跳到該字符串之后並printf
其內容。
char * sub = strstr(arr, string);
sub += strlen(string);
printf("%s\n", sub);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.