【问题标题】:string.Remove doesnt work [duplicate]string.Remove 不起作用[重复]
【发布时间】:2013-02-24 08:08:05
【问题描述】:

我有以下问题:

我写了一个程序,它使用谷歌图像搜索来提取 jpg 文件的链接。但是在链接前面我有一个 15 字符长的字符串,我无法删除。

    public const int resolution = 1920;
    public const int DEFAULTIMGCOUNT = 40;

    public void getimages(string searchpatt)
    {
        string blub = "http://images.google.com/images?q=" + searchpatt + "&biw=" + resolution;
        WebClient client = new WebClient();

        string html = client.DownloadString(blub);                                              //Downloading the gooogle page;
        MatchCollection mc = Regex.Matches(html,
            @"(https?:)?//?[^'<>]+?\.(jpg|jpeg|gif|png)");

        int mccount = 0;                                                                        // Keep track of imgurls 
        string[] results = new string[DEFAULTIMGCOUNT];                                         // String Array to place the Urls 

        foreach (Match m in mc)                                                                 //put matches in string array
        {
            results[mccount] = m.Value;                
            mccount++;
        }

        string remove = "/imgres?imgurl=";
        char[] removetochar = remove.ToCharArray();

        foreach (string s in results)
        {
            if (s != null)
            {
                s.Remove(0, 15);
                Console.WriteLine(s+"\n");
            }
            else { }
        }
       //  Console.Write(html);


    }

我尝试删除和修剪启动,但它们都不起作用,我无法弄清楚我的失败。

我解决了

        for (int i = 0; i < results.Count(); i++)
        {
            if (results[i] != null)
            {
                results[i] = results[i].Substring(15);
                Console.Write(results[i]+"\n");
            }
        }

【问题讨论】:

  • 既然您知道要转储 15 个字符,您可以使用子字符串。
  • 请注意,您的大部分代码实际上与您的问题无关 - 并且您在其中有一些您甚至没有使用的变量。 (你为什么打电话给ToCharArray?)
  • 我不确定我的失败是否会出现在 MatchCollection 中

标签: c# regex string


【解决方案1】:

(我确定这是重复的,但我无法立即找到。)

.NET 中的字符串是不可变的。 string.Removestring.Replace 等方法不会更改 现有 字符串的内容 - 它们返回一个 new 字符串。

所以你想要这样的东西:

s = s.Remove(0, 15);

或者,只需使用Substring

s = s.Substring(15);

【讨论】:

  • 谢谢 :) 我不知道
猜你喜欢
  • 1970-01-01
  • 2016-03-15
  • 1970-01-01
  • 2018-01-04
  • 2013-08-11
  • 2017-07-19
  • 2015-07-04
  • 2012-10-26
  • 2013-01-17
相关资源
最近更新 更多