C#编程(11_修改字符串的内容)

由于字符串是不可变的,因此一个字符串对象一旦创建,值就不能再更改(在不使用不安全代码的情况下)。不过,修改字符串的值然后将结果存储到新的字符串对象中有很多种方法。  System.String   类提供作用于输入字符串并返回新字符串对象的方法。在很多情况下,可以将这个新对象赋给保存原始字符串的变量。System.Text.RegularExpressions.Regex 类提供其他一些以类似方式工作的方法。System.Text.StringBuilder提供一个可“就地”修改的字符缓冲区。调用 StringBuilder.ToString法可新建包含此缓冲区的当前内容的字符串对象。

class ReplaceSubstrings
{
    string searchFor;
    string replaceWith;

    static void Main(string[] args)
    {

        ReplaceSubstrings app = new ReplaceSubstrings();
        string s = "The mountains are behind the clouds today.";

        // Replace one substring with another with String.Replace.
        // Only exact matches are supported.
        s = s.Replace("mountains", "peaks");
        Console.WriteLine(s);
        // Output: The peaks are behind the clouds today.

        // Use Regex.Replace for more flexibility.
        // Replace "the" or "The" with "many" or "Many".
        // using System.Text.RegularExpressions
        app.searchFor = "the"; // A very simple regular expression.
        app.replaceWith = "many";
        s = Regex.Replace(s, app.searchFor, app.ReplaceMatchCase, RegexOptions.IgnoreCase);
        Console.WriteLine(s);
        // Output: Many peaks are behind many clouds today.

        // Replace all occurrences of one char with another.
        s = s.Replace(‘ ‘, ‘_‘);
        Console.WriteLine(s);
        // Output: Many_peaks_are_behind_many_clouds_today.

        // Remove a substring from the middle of the string.
        string temp = "many_";
        int i = s.IndexOf(temp);
        if (i >= 0)
        {
            s = s.Remove(i, temp.Length);
        }
        Console.WriteLine(s);
        // Output: Many_peaks_are_behind_clouds_today.

        // Remove trailing and leading whitespace.
        // See also the TrimStart and TrimEnd methods.
        string s2 = "    I‘m wider than I need to be.      ";
        // Store the results in a new string variable.
        temp = s2.Trim();
        Console.WriteLine(temp);
        // Output: I‘m wider than I need to be.

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }

    // Custom match method called by Regex.Replace
    // using System.Text.RegularExpressions
    string ReplaceMatchCase(Match m)
    {
        // Test whether the match is capitalized
        if (Char.IsUpper(m.Value[0]) == true)
        {
            // Capitalize the replacement string
            // using System.Text;
            StringBuilder sb = new StringBuilder(replaceWith);
            sb[0] = (Char.ToUpper(sb[0]));
            return sb.ToString();
        }
        else
        {
            return replaceWith;
        }
    }
}

若要使用数组表示法访问字符串中的各个字符,可以使用 StringBuilder 对象,该对象重载 [] 运算符以提供对其内部字符缓冲区的访问。也可以使用 ToCharArray方法将该字符串转换为一个字符数组。下面的示例使用 ToCharArray 创建该数组。后修改该数组中的某些元素。后再调用采用一个字符数组作为输入参数的字符串构造函数来创建一个新字符串。

class ModifyStrings
{
    static void Main()
    {
        string str = "The quick brown fox jumped over the fence";
        System.Console.WriteLine(str);

        char[] chars = str.ToCharArray();
        int animalIndex = str.IndexOf("fox");
        if (animalIndex != -1)
        {
            chars[animalIndex++] = ‘c‘;
            chars[animalIndex++] = ‘a‘;
            chars[animalIndex] = ‘t‘;
        }

        string str2 = new string(chars);
        System.Console.WriteLine(str2);

        // Keep the console window open in debug mode
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
  The quick brown fox jumped over the fence
  The quick brown cat jumped over the fence
*/

下面的示例针对的是一种非常罕见的情况,即您可能希望使用不安全代码以类似于 C 样式字符数组的方式就地修改字符串。此示例演示如何使用 fixed 关键字“就地”访问各个字符。  此外还演示对字符串进行不安全操作可能产生的一个副作用,此副作用是由于 C# 编译器在内部存储(暂存)字符串的方式而导致的。通常,除非绝对必要,否则不应该使用这种方法。

class UnsafeString
{
    unsafe static void Main(string[] args)
    {
        // Compiler will store (intern)
        // these strings in same location.
        string s1 = "Hello";
        string s2 = "Hello";

        // Change one string using unsafe code.
        fixed (char* p = s1)
        {
            p[0] = ‘C‘;
        }

        //  Both strings have changed.
        Console.WriteLine(s1);
        Console.WriteLine(s2);

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }

}

From the MSDN.

时间: 2024-08-04 14:10:20

C#编程(11_修改字符串的内容)的相关文章

c#编程基础之字符串函数

c#常用的字符串函数 例一: 获取字符串的大小写函数 ToLower():得到字符串的小写形式 ToUpper():得到字符串的大写形式 注意: 字符串时不可变的,所以这些函数都不会直接改变字符串的内容,而是把修改后的字符串通过函数返回值的形式返回. 源码如下: using System; using System.Collections.Generic; using System.Text; namespace 字符串函数学习 { class Program { static void Mai

c#编程基础之字符串基础

1.C#中单个的字符串用单引号包含就是char类型,('a'),单引号中放且只能放一个字符 2.单个字符也可以表示为字符串,还可以有长度为0的字符串. 3.使用s.Length属性来获得字符串中的字符个数. 4.string 可以看做是char类型的只读数组.char c=s[1];例子:遍历输出string中的每个元素. 5.c#中字符串有一个重要的特性:不可变性.字符串一旦声明,就不再可以改变. 所以只能通过索引来读取指定位置的char,不能对指定位置的char进行修改. 6.如果要对cha

Python黑帽编程2.3 字符串、列表、元组、字典和集合

Python黑帽编程2.3  字符串.列表.元组.字典和集合 本节要介绍的是Python里面常用的几种数据结构.通常情况下,声明一个变量只保存一个值是远远不够的,我们需要将一组或多组数据进行存储.查询.排序等操作,本节介绍的Python内置的数据结构可以满足大多数情况下的需求.这一部分的知识点比较多,而且较为零散,需要认真学习. 2.3.1  字符串 字符串是 Python 中最常用的数据类型.我们可以使用引号('或")来创建字符串. 创建字符串很简单,只要为变量分配一个值即可.例如: var1

java编程思想-字符串

1.不可变 String类初始化后是不可变的(immutable),首先,我建议先看看String类的源码实现,这是从本质上认识String类的根本出发点.从中可以看到: 1.String类是final的,不可被继承.public final class String. 2.String类是的本质是字符数组char[], 并且其值不可改变.private final char value[]; 然后打开String类的API文档,可以发现: 3.String类对象有个特殊的创建的方式,就是直接指

No.32 将字符串进行内容替换

将字符串进行内容替换.注意:修改后变成新字符串,并不是将原字符串直接修改. String replace(oldChar,newChar); String replace(oldstring,newstring);

【编程题目】字符串的排列(字符串)★

53.字符串的排列(字符串).题目:输入一个字符串,打印出该字符串中字符的所有排列.例如输入字符串 abc,则输出由字符 a.b.c 所能排列出来的所有字符串abc.acb.bac.bca.cab 和 cba. 这道题花了我一天,要好好总结! 思路:这道题目感觉有些难,主要是字符串中的字符可能会有重复.我的想法是把一共有多少种字符和每种字符出现的次数统计出来,每个位置对这些字符变量,下一个位置的可用字符减小,再遍历. /* 53.字符串的排列(字符串). 题目:输入一个字符串,打印出该字符串中字

[SHELL] 修改xml的内容

解析和修改xml用python比较方便,但如果不方便使用python,可以用sed命令简单替换 例如,欲替换下面一行中的端口号的值: <param name="ftpPort">21</param> 可以使用: new_port="22" sed '/\<ftpPort\>/s/[0-9]\{2,5\}/'"$new_port"'/' old.xml > new.xml 说明: <和>用于单词

编程题:字符串输出函数puts()

#include<stdio.h> void main() {char str1[]="student",str2[]="teacher"; puts(str1);puts(str2); printf("%s",str1); printf("%s\n%s\n",str1,str2); } 编程题:字符串输出函数puts(),布布扣,bubuko.com

编程题:字符串的指针引用。用指针法实现。功能:将字符串str2复制连接到str1

#include<stdio.h> void main() { char *s1,*s2, str1[30]="beijing",str2[10]="China"; for(s1=str1;*s1!='\0';s1++); for(s2=str2;*s2!='\0';) *s1++=*s2++; *s1='\0'; printf("%s\n",str1); } 编程题:字符串的指针引用.用指针法实现.功能:将字符串str2复制连接到s