首页 > 后端开发 > C++ > 正文

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

WBOY
发布: 2023-08-25 22:53:09
转载
1418人浏览过

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

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号