2017-06-15 45 views
-3

我是C#编程新手。我以前写过Javascript。我想像在JavaScript中一样替换C#中的文本。这里是我的JavaScript代码:我如何在c#中替换类似javascript的文本...?

var str = "this is my text"; 
str = str.replace(/\b(\w)/g,function(matched){ 
    return matched.toUpperCase(); 
}); 

这是如何在C#中完成的?在此先感谢,并为我可怜的英语感到抱歉。

+0

参见[正则表达式(https://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex(V = VS。 110).aspx) – Igor

回答

1

你可以这样说:

using System; 
using System.Text.RegularExpressions; 

class Program { 
    static void Main() { 
     string text = "this is my text"; 

     Regex rx = new Regex(@"\b(\w)"); 

     string result = rx.Replace(text, (Match m) => { 
       return m.ToString().ToUpper().ToString(); 
     }); 

     Console.WriteLine(result);// "This Is My Text" 
     Console.ReadKey(); 
    } 
} 
-1

使用方法与string.replace语法 :

String s = "This is an example."; 
s = s.replace("is","was"); 

小号现在会说:这是一个例子。

+0

他的JS并没有将'is'替换为'was'。这是每首作品的首字母大写 –

0

在你的JS代码中,你想要大写每个单词的第一个字母。在C#中,最好以不同的方式来完成。

string lipsum1 = "this is my text"; 

// Creates a TextInfo based on the "en-US" culture. 
TextInfo textInfo = new CultureInfo("en-US",false).TextInfo; 

// Changes a string to titlecase. 
Console.WriteLine("\"{0}\" to titlecase: {1}", 
        lipsum1, 
        textInfo.ToTitleCase(lipsum1)); 

// Will output: "this is my text" to titlecase: This Is My Text 
0

有几种情况下,您替换字符串:

  1. 每个实例都被替换这是非常重要的。 Replace方法更改指定子字符串的每个实例。我们必须将结果分配给一个变量。

    using system; 
    class Program 
    { 
        static void Main() 
        { 
        const string s = "Coding code is about writing Coding code the 
            right way"; 
        Console.WriteLine(s); 
        string v = s.Replace("Coding", "Testing"); 
        Console.WriteLine(v); 
        } 
    } 
    

//输入:编码代码是如何编写编码代码的正确方法

//输出:测试代码是如何编写测试代码的正确方法

  • 替换一个单一的字符串用一个新的单词替换单词(和下面的空格)。我们分配给替换方法的结果。

    using System; 
    class Program 
    { 
        static void Main() 
        { 
        const string input = "key logger"; 
        Console.WriteLine("::BEFORE::"); 
        Console.WriteLine(input); 
        string output = input.Replace("key ", "keyword "); 
        Console.WriteLine("::AFTER::"); 
        Console.WriteLine(output);  
        } 
    } 
    
  • //输出:

    :: BEFORE :: 键盘记录

    :: AFTER :: 关键字记录器

  • 使用StringBuilder替换字符串

    using System; 
    using System.Text; 
    
    class Program 
    { 
        static void Main() 
        { 
        const string s = "This is an example."; 
    
        // Create new StringBuilder from string. 
        StringBuilder b = new StringBuilder(s); 
        Console.WriteLine(b); 
    
        // Replace the first word. 
        // ... The result doesn't need assignment. 
        b.Replace("This", "Here"); 
        Console.WriteLine(b); 
    
        // Insert the string at the beginning. 
        b.Insert(0, "Sentence: "); 
        Console.WriteLine(b); 
        } 
    } 
    
  • 输出:

    这是一个例子。

    这里是一个例子。

    句子:这里是一个例子。