您的位置:首页 > Web前端

写一个函数,将其中的 都转换成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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iostream string file buffer c
相关文章推荐