簡體   English   中英

操作 C 風格的字符串

[英]Manipulating C-style strings

我需要編寫一個修改 C 字符串的函數,如下所示:

void foo(const char* input, ostream& fout);
//foo("test", std::cout) -> "test est st t "
//foo("hi_world", std::cout) -> "hi_world i_world world orld rld ld d "

該函數每次只打印字符串並刪除第一個字符。 如果刪除的字符是下划線,則該函數不會打印。

這是我到目前為止所擁有的:

void foo(const char* input, ostream& fout) {
    char * answer;

    while(*input) {
        if(*input == '_') {
            //somehow do nothing
        }
        if(input > input[0] {
            fout << *input+1
        }
        else {
            fout << *input << " ";
        }
    }

我不得不改變我的答案,因為我第一次誤讀了這個問題,但我認為這會滿足你的要求。

// Example program
#include <iostream>
#include <cstring>
#include <cstdio>

void foo(const char* input, std::ostream& fout) {
    char* answer;

   for(int n = 0; n < strlen(input); n++){
       answer = (char*)&input[n];

       while (*answer){

            if (*answer != '_') {
                fout << *answer;
            }
            
            answer++;
        }

       fout << " ";
   }

   fout << "\n"; // Assuming you want a newline at the end.
}


int main(){
    const char* phrase = "test\0";
    const char* phrase2 = "hi_world\0";
    
    foo(phrase, std::cout);
    foo(phrase2, std::cout);
    
    return 0;
}

運行它會產生以下輸出。

$ ./answer 
test est st t 
hiworld iworld world world orld rld ld d 

您需要每次通過循環增加input以更改字符串的起始索引。

使用continue; 如果第一個字符是_則跳過迭代。

要打印字符串,請使用fout << input fout << *input只會打印一個字符,而不是整個字符串。

void foo(const char* input, ostream& fout) {
    for(; *input; input++) {
        if(input[0] == '_') {
            continue;
        }
        fout << input << " ";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM