zoukankan      html  css  js  c++  java
  • 有关替换字符的代码问题


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

    #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();
    

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

  • 相关阅读:
    【面试题037】两个链表的第一个公共结点
    【面试题036】数组中的逆序对
    【面试题035】第一个只出现一次的字符
    WebService 序列化和反序列化
    Cookies设置,获取,删除
    Session 存储和失效方式
    Render 使用
    批量保存 htm
    js属性prototype的使用
    水晶报表 IE设置
  • 原文地址:https://www.cnblogs.com/Zerozzx/p/7436901.html
Copyright © 2011-2022 走看看