我正在嘗試撰寫一個從字串中提取注釋的函式。例如,給定:
"this is a test //bread is great"
它回傳:
"bread is great"
我試圖計算字符數直到第一個 ' //' 出現,然后修剪字串中不需要的部分。
while(s[i] != '/' && s[i 1] != '/') {
newbase ;
i ;
}
它適用于第一個示例,但如果給我這樣的字串,我就會遇到問題:
"int test = 2/3"
它應該回傳""(一個空字串),但它沒有。我不明白。
uj5u.com熱心網友回復:
這是非常基本的字串處理。簡單地使用strstr,如果成功,使用結果。(可選)將其復制到第二個字串。
#include <stdio.h>
#include <string.h>
int main (void)
{
const char* str = "this is a test //bread is great";
const char* result = strstr(str,"//");
if(result != NULL)
{
result = 2; // skip the // characters
puts(result); // print the string
// optionally make a hardcopy
char some_other_str[128];
strcpy(some_other_str, result);
puts(some_other_str);
}
}
uj5u.com熱心網友回復:
如果您只想在第一次出現后天真地提取剩余的字串,"//"您可能需要這樣的東西:
#include <stdio.h>
#include <string.h>
int main()
{
const char *text = "this is a test //bread is great";
const char* commentstart = strstr(text, "//");
char comment[100] = { 0 }; // naively assume comments are shorter then 99 chars
if (commentstart != NULL)
{
strcpy(comment, commentstart 2);
}
printf("Comment = \"%s\"", comment);
}
免責宣告:
- 這是未經測驗的簡單代碼,顯示了一種可能的方法。沒有任何錯誤檢查,尤其是當注釋超過 99 個字符時,會出現緩沖區溢位。
- 這段代碼絕對不適合從現實生活中的 C 代碼中提取注釋。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/378665.html
標籤:C
下一篇:接收資料流的UART同步演算法
