替换 C# 中的部分字符串 [英] replace part of the string in C#

查看:42
本文介绍了替换 C# 中的部分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多字符串,它们有多个空格和一个正斜杠,如下所示:

I have many strings which have multiple spaces and one forward slash like this:

string a="xxxxxx xxx xxxxxxxx xxxxxx aaa/xxxxxxxxxxxxxxx";

string b="xxxx xxx xxxxxx bbbbb/xxxxxxx xxx";

string c="xx xx 12345/x xx"

我需要做的是用新字符串替换子字符串aaa"或bbbbb"或12345"(请注意,子字符串只是示例,它们可以是任何东西)我想要.
子字符串aaa"或bbbbb"或12345"或任何东西的特征是子字符串就在唯一一个正斜杠之前,就在该斜杠前面和最接近该斜杠的空格之后.

What I need to do is to replace the substring "aaa" or "bbbbb" or "12345" (Please note that the substrings are just examples, they can be anything) with the new string I want.
The feature for the substring "aaa" or "bbbbb" or "12345" or anything is that the substring is right before the only one forward slash and right after the space in front of and closest to this slash.

我如何定位这个子字符串以便我可以用我想要的新子字符串替换它?谢谢.

How do I locate this substring so that I can replace it with the new substring I want? Thanks.

推荐答案

好吧好吧

采用通用方法:

        public string Replacement(string input, string replacement)
        {
            string[] words = input.Split(' ');
            string result = string.Empty;

            for (int i = 0; i < words.Length; i++)
            {
                if(words[i].Contains('/'))
                {
                    int barIndex = Reverse(words[i]).LastIndexOf('/') + 1;
                    int removeLenght = words[i].Substring(barIndex).Length;
                    words[i] = Reverse(words[i]);
                    words[i] = words[i].Remove(barIndex, removeLenght);
                    words[i] = words[i].Insert(barIndex, Reverse(replacement));
                    string ToReverse = words[i];
                    words[i] = Reverse(ToReverse);

                    break;
                }
            }

            for(int i = 0; i < words.Length; i++)
            {
                result += words[i] + " ";
            }

            result = result.Remove(result.Length - 1);

            return result;
        }

        public string Reverse(string s)
        {
            char[] charArray = s.ToCharArray();
            Array.Reverse(charArray);
            return new string(charArray);
        }

为了回应>>我需要一个通用的方法来替换斜线和最接近它的空间之间的任何东西

In reponse to >> I need a universal method to replace any stuff between the slash and the space closest to it

这篇关于替换 C# 中的部分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆