字符串是一组字符。我们也可以将它们称为字符数组。考虑到 一个由字符串组成的字符数组,这些字符串具有指定的索引和值。有时候 我们可以对字符串进行一些修改,其中一种修改是替换字符 通过提供一个特定的索引。在本文中,我们将看到如何替换一个字符从一个 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。在其中没有范围可以通过分配新字符来替换其中的字符 In 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中文网其他相关文章!