首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >文本编辑小程序

文本编辑小程序
EN

Stack Overflow用户
提问于 2022-11-24 10:43:13
回答 2查看 34关注 0票数 -2

程序应该返回编辑文本,在那里您必须将“-”、“”改为"\t“。

这里的问题是结果

代码语言:javascript
复制
Input: Китай: 1405023000; 24.08.2020; 17.99%

Expected    Китай   1405023000  24.08.2020  17.99%

Myne        Китай:  1405023000; 24.08.2020; 17.99%

因此,出于某种原因,我认为他扰乱了stringSeparators元素的顺序或什么的。我对这一刻很感兴趣

代码语言:javascript
复制
public static string ReplaceIncorrectSeparators(string text)
{
    string populationEdited = "";
    string[] stringSeparators = new string[] {" - ", ": ", "; ", ", ", " "};
    for (int i = 0; i < stringSeparators.Length; i++)
    {
        populationEdited = text.Replace(stringSeparators[i], "\t");
    }

    return populationEdited;
}

我已经用另一种方式解决了这个问题,但是我想用分离器来解决它。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-11-24 10:47:46

代码中的主要问题是它没有正确地存储Replace的结果。这应该能起作用:

代码语言:javascript
复制
public static string ReplaceIncorrectSeparators(string text)
{
    string populationEdited = text; // You need to start with the original
    string[] stringSeparators = new string[] {" - ", ": ", "; ", ", ", " "};
    for (int i = 0; i < stringSeparators.Length; i++)
    {
        // And here instead of text.Replace you do populationEdited.Replace
        populationEdited = populationEdited.Replace(stringSeparators[i], "\t");
    }

    return populationEdited;
}
票数 2
EN

Stack Overflow用户

发布于 2022-11-24 10:59:57

你可以用Regex作为替代方案。这将使您的代码更短(在我看来更易读)。

代码语言:javascript
复制
public static string ReplaceIncorrectSeparators(string text)
{
    Regex regex = new Regex(@" - |: |; |, | ");
    return regex.Replace(text, "\t");
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74559440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档