• 有关替换字符的代码问题



    代码用来使用“,”替换空格。

    #include <iostream>
    #include <fstream>
    #include <string>
    #include <stdlib.h>
    using namespace std;
    void main() {
        string file_path = "test.txt";//文件路径
        string out_path = "ttttt.txt";//输出路径
        string str;
        string::size_type pos = 0;
        ifstream instream;
        ofstream outstream;
        instream.open(file_path);
        if (!instream)
            cout << "error" << endl;
        outstream.open(out_path);
        while (getline(instream,str)) {
            pos = str.find(" ");//查找字符在string中第一次出现的位置
            while (pos != string::npos)//判断是否存在“hyu”这个字符
            {
                str.replace(pos, 1, ",");//用,替换 .
                
                pos = str.find(" ", pos + 1);//查找剩余字符串
            }
            outstream << str << endl;
    
        }
        instream.close();
        outstream.close();
        system("pause");
    
    }

     此代码可行。

    接下来的代码则不可行。

    void main() {
    	
    	string str=" ";
    	string line;
    	string::size_type pos = 0;
    	string target=",";
    	ifstream instream;
    	ofstream outstream;
    	instream.open("test.txt");
    	outstream.open("ttttt.txt");
    	while (getline(instream, line)) {
    		pos = str.find(str);//查找字符在string中第一次出现的位置
    				while (pos != string::npos)// 判断有没找到
    		{
    			line.replace(pos, str.size(), target);//替换字符串
    			pos = line.find(str, pos + 1);//查找剩余匹配字符
    
    		}
    			
    			outstream << str << endl;
    		
    	}
    	instream.close();
    	outstream.close();
    

     这一段代码 会导致死循环 ,原因 个人猜测可能是应为空格符比较特殊的原因。

  • 相关阅读:
    elasticsearch插件开发
    elasticsearch启动流程
    HBase结构
    Scala统计一个文件所有单词出现的次数
    es基础知识
    Linux中Swap与Memory内存简单介绍
    linux 常用命令
    巅峰对决之Swarm、Kubernetes、Mesos
    【JS】JS知识小结
    【HTTP】HTTP状态码详解
  • 原文地址:https://www.cnblogs.com/Zerozzx/p/7436901.html
Copyright © 2020-2023  润新知