#include<iostream>
using namespace std;
int main()
{
char str1[50]="I am a happy boy\'s daddy.",str2[50];
int i=0,j=0;
while(str1[i]!='\0')
{
str2[j]=str1[i];
j++;
i++;
}
str2[j]='\0';//切记!!
cout<<"整理后的字符串"<<str2<<endl;
return 0;
}
复制字符串
http://blog.csdn.net/sxhelijian/article/details/8295129 上有其他方法
gets()需要#include <stdio.h>,否则报错
连接两个字符串
#include <stdio.h>
#include<iostream>
using namespace std;
int main()
{
char str2[50];
char str[20]={"第二个字符串"};
int i=0,j=0;
cout<<"输入字符串:";
gets(str2);
while(str2[i]!='\0')
{
i++;
}
while(str[j]!='\0')
{
str2[i++]=str[j++];
}
str2[i]='\0';
cout<<"--------------------------"<<endl;
cout<<"处理后的字符串是: "<<str2<<endl;
return 0;
}
连接后,放入字符串3
#include <stdio.h>
#include<iostream>
using namespace std;
int main()
{
char str2[50],str3[100];
char str[50]={"第二个字符串//comment:"};
int i=0,j=0;
cout<<"输入字符串:";
gets(str2);
while(str2[i]!='\0')
{
i++;
}
while(str[j]!='\0')
{
str2[i++]=str[j++];
}
str2[i]='\0';
for(i=0,j=0;str2[i]!='\0';i++)
{
str3[j]=str2[i];
j++;
}
str3[i]='\0';
cout<<"--------------------------"<<endl;
cout<<"处理后的字符串3是: "<<str3<<endl;
return 0;
}
或者
#include <stdio.h>
#include<iostream>
using namespace std;
int main()
{
char str2[50],str3[100];
char str[50]={"第二个字符串//comment:"};
int i=0,j=0;
cout<<"输入字符串:";
gets(str2);
while(str2[i]!='\0')
{
str3[i]=str2[i];
i++;
}
while(str[j]!='\0')
{
str3[i++]=str[j++];
}
str3[i]='\0';
cout<<"--------------------------"<<endl;
cout<<"处理后的字符串3是: "<<str3<<endl;
return 0;
}
去掉多余的空格(以下为例子)
#include <stdio.h>
#include<iostream>
using namespace std;
int main()
{
char str[]=" Only one space is allowed between the two words.";
cout<<"原始难看的句子:"<<str<<endl;
int i=0,j=0;
bool notSpace;
while(str[j]==' ')//忽略开始的若干个空格
j++;
notSpace=true;
while(str[j]!='\0')
{
if (str[j]!=' ')
{
notSpace=true;
str[i++]=str[j++]; // 不是空格,复制
}
else if (notSpace) //是空格,但目前是第一个(因为之前notSpace=true;的条件是遇非空格)
{
notSpace=false; //第一个空格仍然要复制
str[i++]=str[j++];
}
else //如遇第二个或更后的空格,正是由于遇到第一个空格并复制后,notSpace=false;的原因,会走到这儿
{
j++; //不复制
}
}
str[i]='\0';
cout<<"整理后的句子是:"<<str<<endl;
return 0;
}
在字符串前加5个符号"note:"
#include <stdio.h>
#include<iostream>
using namespace std;
int main()
{
char str1[40]={"I am a boy."};
char str2[20]={"note:"};
int i=0,len2=0;
//下面将把str2插入到str1的开头部分,并且保存在str1中
//先求出str2的“长度”
while(str2[len2]!='\0')
{
len2++;
}
//str2中有len2个字符
//找到str1中结尾的位置
i=0;
while(str1[i]!='\0')
{
i++;
}
//由后往前,整体往后“搬迁”len2个位置
while(i>=0)
{
str1[i+len2]=str1[i];
i--;
}
//空出的前len2位置复制为str2
i=len2-1;
while(i>=0)
{
str1[i]=str2[i];
i--;
}
cout<<"处理后的字符串是: "<<str1<<endl;
return 0;
}