写一个函数,将其中的 都转换成4个空格(四种方法)
2011-09-10 12:25
423 查看
法一:
1. string replaceTab(const string& strSrc)
2. {//strSrc 源字符串, 将源字符串中的'/t'转换为4个空格
3. string strDes;
4. for (int i=0; i!=strSrc.size(); i++)
5. {
6. if (strSrc[i] == '/t') //转换成4个空格
7. {
8. strDes += " ";
9. }
10. else
11. {
12. strDes += strSrc[i];
13. }
14. }
15. return strDes;
16. }
法二:
#include <iostream>
#include <string>
using namespace std;
bool change(char *buf, int len)
{ int count = 0;
int i;
// 统计有多少个'\t'
for (i = 0; buf[i] != '\0'; i++) {
if (buf[i] == '\t')
count++;
}
// 给定的buf空间是否能装下生成的字符串
int j = i + 3 * count;
if (len < j + 1)
return false;
// 从后向前逐个替换
while (count > 0)
{
while (buf[i] != '\t')
buf[j--] = buf[i--];
count--;
buf[j] = buf[j - 1] = buf[j - 2] = buf[j - 3] = ' ';
j -= 4;
i--;
}
return true;
}
int main() {
char buf[100] = "123\t45\t\t\t6\t\t65\n4234\t5345";
// buf是原字符串,100是buf的长度(要足够大,最好是原字符串的3倍)
if (change(buf, 100) == true)
cout << buf << endl;
}
三:
#include<iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file("sample.cpp");
if(!file.good())
cout<<"file opened failed"<<endl;
const int N = 10000;
//~ buffer大小可根据文件定义
char buf ;
size_t pos = 0;
while(file.get(buf[pos++]));
file.clear();
file.seekp(0);
for(size_t i = 0; i < pos; ++i)
{
if(buf[i] == '\t')
file<<" "<<flush;
else
file<<buf[i]<<flush;
}
file.close();
//system("pause");
return 0;
}
四:
#include <iostream> #include <string> using namespace std; int main() { string s= "dasfas\tfdasfsdaf\tdfsdfa "; int c=0; while((c=s.find( "\t ",c+1))!=string::npos) { s.replace(c,1, " "); }cout < <s < <endl; return 0; } |
相关文章推荐
- 写一个函数,将其中的 \t 都转换成4个空格
- 写一个函数,将其中的/t都转换成4个空格。
- 写一个函数,将其中的/t都转换成4个空格。(C++版)
- 编程题:写一个函数将其中的\t都转换成4个空格
- 作业题:输入4个整数,找出其中最大的数。用一个函数来实现. 分别使用结构化方法和函数嵌套的方法。
- c++经典题目:写个函数,将其中的\t都转换成4个空格
- 写一个函数,将其中的 都转换成4 个空格。
- 一个javascript的Math对象的方法实现,将字符串,转换成实际函数
- 8.8 写一个函数,输入一个4位数字, 要求输出这4个数字字符, 但每两个数字间有一个空格。 如输入1990,应输出“1 9 9 0”。
- 8.6 编写一个类,其中有一个 double 型私有数据成员 yuan(存放人民币数量,单位 为元),另外包含一个转换运算符重载成员函数以将 yuan 转换成美元(假设 1 美元对换 8.268 人民
- 练习 3-6 修改itoa函数,使得该函数可以接收三个参数。其中,第三个参数为最小字段宽度。为了保证转换后所得的结果至少具有第三个参数指定的最小宽度,在必要时应在所得结果的左边填充一定的空格。
- 【廖雪峰 python教程 课后题 切片】利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:
- 设计一个函数,输入一个4位数字,要求输出这4个数字字符,但每个数字间空一个空格。
- Oracle中将数字转换成字符插入表中会多一个空格的解决方法
- 用一个函数实现将一行字符串中最短的单词输出。此行字符串从主函数传递给该函数。假设字符串中包含的单词以空格作为分隔符号,例如”Asia Games 2010 is held in GuangZhou.”,其中最短的单词是”is”和”in”。
- 分享四种将PDF文件转换为CAD文件的方法,总有一个方法适合你
- 【廖雪峰 python教程 课后题 切片】利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:
- 习题 7.8 写一个函数,输入一个4位数字,要求输出这4个数字字符,但每两个数字间空一个空格。如输入1990,应输出“1 9 9 0”。
- javascript与cs代码互相调用 asp.net中前台javascript与后台C#交互 这里主要包括了javascipt与后台CS代码四种方法互调(其中包括函数与变量的访问)
- 三种实现交换的方法,其中一个诡异的swap函数——C/C++语言(问题求助)