字串是一組字元。我們也可以將它們稱為字元數組。考慮到 由字串組成的字元數組,這些字串具有指定的索引和值。有時候 我們可以對字串進行一些修改,其中一種修改是替換字符 透過提供一個特定的索引。在本文中,我們將看到如何替換一個字元從一個 specific index inside a string using C .
String_variable[ <given index> ] = <new character>
在C 中,我們可以使用索引來存取字串字元。在這裡用來替換一個字元的程式碼是 在指定的索引位置上,我們只需將該位置賦值為新的某個字符 character as shown in the syntax. Let us see the algorithm for a better understanding.
#include <iostream> using namespace std; string solve( string s, int index, char new_char){ // replace new_char with the existing character at s[index] if( index >= 0 && index < s.length() ) { s[ index ] = new_char; return s; } else { return s; } } int main(){ string s = "This is a sample string."; cout << "Given String: " << s << endl; cout << "Replace 8th character with X." << endl; s = solve( s, 8, 'X' ); cout << "Updated String: " << s << endl; cout << "Replace 12th character with ?." << endl; s = solve( s, 12, '?' ); cout << "Updated String: " << s << endl; }
Given String: This is a sample string. Replace 8th character with X. Updated String: This is X sample string. Replace 12th character with ?. Updated String: This is X sa?ple string.
Replacing characters at a specified index is simple enough in C . C strings are mutable, so we can change them directly. In some other languages like java, the strings are not mutable。在其中沒有範圍可以透過分配新字符來替換其中的字符 在 such cases, a new string needs to be created. A similar will happen if we define strings as 在C語言中,我們可以使用字元指標。在我們的例子中,我們定義了一個函數來取代一個 在給定的索引位置傳回字元。如果給定的索引超出範圍,它將返回 string and it will remain unchanged.
以上是C++程式:取代特定索引處的字符的詳細內容。更多資訊請關注PHP中文網其他相關文章!