簡體   English   中英

替換char數組中的字符C ++

[英]Replacing characters in a char array c++

我有一個用1和0填充的字符數組。 如果1后面有0,則需要切換位置。 循環重復k次。 我寫了這段代碼,但是當我嘗試打印字符串時,它什么也沒打印出來,或者只是打印出1。為什么這樣做和為什么不起作用?

#include <iostream>
using namespace std;
int const limit = 100000;

int main() {
    int k;
    char s[limit];

    cin >> k;
    cin >> s;

    for (int i = 0; i < k; i++) {
        for (int j = 0; j < strlen(s); j++)
            if (s[j + 1] == '0' && s[j] == '1') {
                s[j + 1] = '1';
                s[j] = 0;
                }
            }
    }

    cout << s;

    return 0;
}

a)有一個錯誤的花括號。

b)您需要將s[j] = 0更改為s[j] = '0'

c)盡管不是錯誤,但為澄清起見,我將在第二個for循環周圍添加花括號。 這使代碼更易於閱讀。

#include <cstring>
#include <iostream>

using namespace std;
int const limit = 100000;

int main() {
    int k;
    char s[limit];

    cin >> k;
    cin >> s;

    for (int i = 0; i < k; i++) {
        for (int j = 0; j < strlen(s); j++) {
            if (s[j + 1] == '0' && s[j] == '1') {
                s[j + 1] = '1';
                s[j] = '0';
            }
        }
    }

    cout << s;

    return 0;
}

首先,我將從對上面語句的理解開始: int const limit = 100000; 意味着(您已經知道)您已分配給命名變量“ limit”,一個恆定的整數值100000。值100000是單個數值整數; 不是ASCII字符數組“ 0”和“ 1”(如果我正確地遵循了您的想法)。 數值100000在存儲器中分配了一個位置,無法在代碼中更改; 除非您自己將代碼更改為另一個值(即,int const limit = 15;)。 (沒有意義)。

//我的想法是您是否試圖做這樣的事情?

#include <iostream>
#include <string>

int(main) {
int k = 10;

char s[] = "0 1 0 1 0 1 1 0 1 1":  // let the compiler count

// create a nested for loop to change the '0' char to a '1' char here as you
// want to do above.
.... code ....

return 0;
}

您說您有一個char數組s [limit],由1和0填充。 然后,它們必須是ASCII系統名稱。 '0'和'1'是字符值,而不是整數值,例如在數組聲明s [limit]中。 “限制”是一個整數值; 100000。您的array []被命名為“ s”,它是存儲字符的數據類型“ char”; 您已分配了一個數字值。 (如果我的想法有誤,請更正我,或者可以改善自己的編碼方式)TY>

包括

包括

使用名稱空間std; int const限制= 100000;

int main(){

int k;
char s[limit];



cout << "Enter a k limit: \n" ;
cin >> k;
cout << "You entered: " << k << endl;
cout << "Enter your 0's and 1's. \n";
cin >> s;
cout << "you entered: " << s << '\n';



for (int j = 0; j < k; j++) {
    for (int i = 0; i < sizeof(s); i++) {
        if (s[i + 1] == '0' && s[i] == '1') {
            s[i + 1] = '1';
            s[i] = '0';
        }
    }
    cout << s;

}
return 0;

}

暫無
暫無

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

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