C++程序:替换特定索引处的字符

WBOY
WBOY 转载
2023-08-25 22:53:09 654浏览

C++程序:替换特定索引处的字符

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

算法

  • 取字符串 s,指定索引 i,以及一个新字符 c
  • 如果索引 i 是正数且其值不超过字符串大小,则
    • s[ i ] = c
    • return s
  • otherwise 的中文翻译为:否则
    • 返回s而不改变任何内容
  • end if

Example

#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中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除