字符串是一组字符。我们也可以将它们称为字符数组。考虑到一个由字符串组成的字符数组,这些字符串具有指定的索引和值。有时候我们可以对字符串进行一些修改,其中一种修改是替换字符通过提供一个特定的索引。在本文中,我们将看到如何替换一个字符从一个specific index inside a string using C++.
语法
String_variable[ ] =
登录后复制
在C++中,我们可以使用索引访问字符串字符。在这里用来替换一个字符的代码是在指定的索引位置上,我们只需将该位置赋值为新的某个字符character as shown in the syntax. Let us see the algorithm for a better understanding.
算法
取字符串 s,指定索引 i,以及一个新字符 c如果索引 i 是正数且其值不超过字符串大小,则s[ i ] = creturn sotherwise 的中文翻译为:否则返回s而不改变任何内容end if
Example
#include 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输出
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 notmutable。在其中没有范围可以通过分配新字符来替换其中的字符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++程序:替换特定索引处的字符的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2587558.html