Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#如果字符串不是子字符串,则替换该字符串_C#_Replace_Substring - Fatal编程技术网

c#如果字符串不是子字符串,则替换该字符串

c#如果字符串不是子字符串,则替换该字符串,c#,replace,substring,C#,Replace,Substring,我处理文件是为了用一个pre和一个post字符串(比如“#”和“.”)替换预定义关键字列表,如下所示: “单词2另一个单词和其他一些东西”应该变成“#单词.#单词2.#另一个单词.和其他一些东西” 我的密钥是唯一的,从最长的密钥到最小的密钥都经过了处理,所以我知道“包含”只能启用 但是,如果我有关键字包含(例如Word2包含Word),如果我有 "Word Word2 anotherWord and some other stuff" .Replace("anotherWord", "#

我处理文件是为了用一个pre和一个post字符串(比如“#”和“.”)替换预定义关键字列表,如下所示:

“单词2另一个单词和其他一些东西”应该变成“#单词.#单词2.#另一个单词.和其他一些东西”

我的密钥是唯一的,从最长的密钥到最小的密钥都经过了处理,所以我知道“包含”只能启用 但是,如果我有关键字包含(例如
Word2
包含
Word
),如果我有

"Word Word2 anotherWord and some other stuff"
    .Replace("anotherWord", "#anotherWord.")
    .Replace("Word2", "#Word2.")
    .Replace("Word", "#Word.")
我得到以下结果:

“单词.####单词.2.##另一个##单词..和其他一些东西”

当然,我的方法不是wokring。那么,如果字符串中的某个键不包含在另一个键中,如何确保只替换该键?我尝试了RegExp,但没有找到正确的方法。或者有另一种解决方案?

一种方法是使用

string myString = String.Format("ORIGINAL TEXT {1} {2}", "TEXT TO PUT INSIDE CURLY BRACKET 1", "TEXT TO PUT IN CURLY BRACKET 2");

//Result: "ORIGINAL TEXT TEXT TO PUT INSIDE CURLY BRACKET 1 TEXT TO PUT IN CURLY BRACKET 2"
但是,这首先要求原始文本中有花括号


非常混乱,但是你可以用替换替换你要找的单词,然后同时更换卷曲的背景。可能有更好的方法来实现这一点,但我现在想不起来。

您可以将字符串按“”拆分,然后在字符串数组中循环。将数组的每个索引与替换字符串进行比较,然后在完成时连接它们

string newString = "Word Word2 anotherWord and some other stuff";
string[] split = newString.Split(' ');

foreach (var s in split){
    if(s == "Word"){
        s = "#Word";
    } else if(s == "Word2"){
        s = "#Word2";
    } else if(s == "anotherWord"){
        s = "#anotherWord";
    }
}
string finalString = string.Concat(split);
我建议直接实施,例如:


如果性能不是关键要求,只需使用带单词边界的正则表达式即可:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Subst
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var map = new Dictionary<string, string>{
                {"Word", "#Word."},
                {"anotherWord", "#anotherWord."},
                {"Word2", "#Word2."}
            };
            var input = "Word Word2 anotherWord and some other stuff";

            foreach(var mapping in map) {
                input = Regex.Replace(input, String.Format("\\b{0}\\b", mapping.Key), Regex.Escape(mapping.Value));
            }

            Console.WriteLine(input);
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Text.RegularExpressions;
命名空间子
{
公共课程
{
公共静态void Main(字符串[]args)
{
var-map=新字典{
{“单词”,“单词”},
{“另一个词”,“另一个词。”},
{“单词2”,“单词2.”
};
var input=“Word2其他单词和其他一些东西”;
foreach(映射中的var映射){
input=Regex.Replace(input,String.Format(“\\b{0}\\b”,mapping.Key),Regex.Escape(mapping.Value));
}
控制台写入线(输入);
}
}
}
正则表达式替代方案(顺序无关紧要):

或分开:

string s = "Word Word2 anotherWord and some other stuff";

s = Regex.Replace(s, @"\b" + Regex.Escape("anotherWord") + @"\b", "#anotherWord.");
s = Regex.Replace(s, @"\b" + Regex.Escape("Word2")       + @"\b", "#Word2.");
s = Regex.Replace(s, @"\b" + Regex.Escape("Word")        + @"\b", "#Word.");

使用两个循环通过的方法解决了问题,如下所示

List<string> keys = new List<string>();
keys.Add("Word1"); // ... and so on
// IMPORTANT: algorithm works only when we are sure that one key cannot be
//            included in another key with higher index. Also, uniqueness is
//            guaranteed by construction, although the routine would work
//            duplicate key...!
keys = keys.OrderByDescending(x => x.Length).ThenBy(x => x).ToList<string>();
// first loop: replace with some UNIQUE key hash in text
foreach(string key in keys) {
  txt.Replace(key, string.Format("!#someUniqueKeyNotInKeysAndNotInTXT_{0}_#!", keys.IndexOf(key)));
}
// second loop: replace UNIQUE key hash with corresponding values...
foreach(string key in keys) {
  txt.Replace(string.Format("!#someUniqueKeyNotInKeysAndNotInTXT_{0}_#!", keys.IndexOf(key)), string.Format("{0}{1}{2}", preStr, key, postStr));
}
List key=new List();
关键字。添加(“单词1”);/。。。等等
//重要提示:只有当我们确定一个密钥不能被删除时,该算法才起作用
//包含在另一个索引更高的键中。此外,独特性也很重要
//由施工保证,尽管常规工作可行
//重复的钥匙。。。!
keys=keys.OrderByDescending(x=>x.Length).ThenBy(x=>x.ToList();
//第一个循环:替换为文本中的某个唯一密钥散列
foreach(字符串键入键){
替换(key,string.Format(“!#someuniquekeynotinkeyandnotintxt{0}#!”,key.IndexOf(key));
}
//第二个循环:用相应的值替换唯一密钥哈希。。。
foreach(字符串键入键){
txt.Replace(string.Format(“!#someuniquekeynotinkeyandnotintxt{0}#!”,keys.IndexOf(key)),string.Format(“{0}{1}{2}”,preStr,key,postStr));
}

选择标记时请密切注意,以免选择错误的标记。请使用正确的语言标记问题,这不是字符串替换的工作方式。您可能希望用另一个临时字符串替换搜索字符串,然后在所有搜索完成后再次替换所有内容。假设您有
。替换(“bob”)、“#bob”)。替换(“cat”、“#cat”)
如果输入是山猫bob cabobt bocatb,您希望得到什么结果?@ScottHannen:这不是一个现实的解决方案。做一半的工作并声称其余的工作不应该做与做必要的工作是不同的。对于示例代码,可以有效地删除“Word2”替换,因为“Word”替换也会命中“Word2”,但如果使用不同的替换值(例如,将“Word”替换为“#Word”,但将“Word2”替换为“@Word2”)。(1)在技术上可行的情况下,使用
String.Format
符号预先设置输入值的格式实际上是将输入绑定到特定的实现,这不是好的设计。(2) 这还意味着输入句子的人知道所有占位符和占位符列表的顺序,这需要最终用户提供大量的知识,并且经常会破坏这样一个自动化任务的目的。(3) 此外,您的代码甚至无法工作,因为String.Format是零索引的。这取决于原始用户需要这样做。他可能正在尝试填充现有模板,在这种情况下,这将是完美的。至于说我的代码不起作用。为您更新:请注意,空格可能不是唯一的分隔符。逗号、句点、分号、引号等。。。您的答案从技术角度来看是有效的,但可能无法涵盖所有需要的情况。不,关键可能是多个单词(同意,忘了提及!)接近我的解决方案,它不使用正则表达式,因为,我必须诚实地说,我对它们的了解还不够。。。!
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace Subst
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var map = new Dictionary<string, string>{
                {"Word", "#Word."},
                {"anotherWord", "#anotherWord."},
                {"Word2", "#Word2."}
            };
            var input = "Word Word2 anotherWord and some other stuff";

            foreach(var mapping in map) {
                input = Regex.Replace(input, String.Format("\\b{0}\\b", mapping.Key), Regex.Escape(mapping.Value));
            }

            Console.WriteLine(input);
        }
    }
}
var result = Regex.Replace("Word Word2 anotherWord and some other stuff", @"\b\S+\b", m => 
    m.Value == "anotherWord" ? "#anotherWord." : 
    m.Value == "Word2" ? "#Word2." :
    m.Value == "Word" ? "#Word." : m.Value)
string s = "Word Word2 anotherWord and some other stuff";

s = Regex.Replace(s, @"\b" + Regex.Escape("anotherWord") + @"\b", "#anotherWord.");
s = Regex.Replace(s, @"\b" + Regex.Escape("Word2")       + @"\b", "#Word2.");
s = Regex.Replace(s, @"\b" + Regex.Escape("Word")        + @"\b", "#Word.");
List<string> keys = new List<string>();
keys.Add("Word1"); // ... and so on
// IMPORTANT: algorithm works only when we are sure that one key cannot be
//            included in another key with higher index. Also, uniqueness is
//            guaranteed by construction, although the routine would work
//            duplicate key...!
keys = keys.OrderByDescending(x => x.Length).ThenBy(x => x).ToList<string>();
// first loop: replace with some UNIQUE key hash in text
foreach(string key in keys) {
  txt.Replace(key, string.Format("!#someUniqueKeyNotInKeysAndNotInTXT_{0}_#!", keys.IndexOf(key)));
}
// second loop: replace UNIQUE key hash with corresponding values...
foreach(string key in keys) {
  txt.Replace(string.Format("!#someUniqueKeyNotInKeysAndNotInTXT_{0}_#!", keys.IndexOf(key)), string.Format("{0}{1}{2}", preStr, key, postStr));
}