如何在数组的开头插入字符? [英] How to insert character at the beginning of an array?

查看:104
本文介绍了如何在数组的开头插入字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个char数组,我需要将所有内容都移动1并在开头插入".关于如何执行此操作的任何想法?

I have a char array and I need to move everything by 1 and insert " " at the beginning. Any thoughts on how to do this?

推荐答案

错误的主意.这种操作的性能将受到损害.如果确实需要插入元素,请考虑使用其他旨在更有效地执行此操作的数据类型,尤其是std::vector:
http://www.cplusplus.com/reference/stl/vector/ [ http://www.cplusplus.com/reference/stl/vector/insert/ [ ^ ].

—SA
Bad idea. Performance of such operation will be compromised. If you really need to insert element, consider using different data type designed to do this operation more efficiently, in particular, std::vector:
http://www.cplusplus.com/reference/stl/vector/[^],
http://www.cplusplus.com/reference/stl/vector/insert/[^].

—SA


为什么不使用std :: string类?
basic_string ::插入 [
Why not use the std::string class?
basic_string::insert[^]

std::string s("Test");
s.insert(0,1,'' '');
s.insert(0,1,''A'');



只要我们有一个字符串类,就可以使用它:-D

[更新]
您还可以使用
内存 [



As long as we have a string class, it kind of make sense to use it :-D

[Update]
You can also use memmove[^]

#include <memory.h>
#include <string.h>
#include <stdio.h>

char strTest[5] = "Test";
char buffer[260];

int main( void )
{
   memset(buffer,0,sizeof(buffer))
   
   printf( "The string: %s\n", strTest );
   memcpy( buffer, strTest, 4 );
   printf( "The Buffer: %s\n", buffer );

   memmove( buffer + 2, buffer, 4 );
   buffer[0] = ''A'';
   buffer[1] = '' '';

   printf( "The Buffer: %s\n", buffer );
}


for(int i =0;i < len; i++)
str[i+1] = str[i];
str[0] = 'a'


这篇关于如何在数组的开头插入字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆