【问题标题】:Property or indexer cannot be assigned to - it is read only.C#无法分配属性或索引器 - 它是只读的。C#
【发布时间】:2020-11-19 09:17:21
【问题描述】:

我想通过 C# 编写一个程序,将给定字符串的每个单词的首字母大写。 它给了我一个错误:不能将属性或索引器分配给-它是只读的。 当我使用 ToUpper 时,错误是:“ToUpper 在当前上下文中不存在”。

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;

namespace Csharp_Training
{
    class Program
    {
        static string Captilaize(string Text)
        {
            for (int i = 0; i < Text.Length; i++)
            {
                if (i == 0)
                {
                    Text[i] = ToUpper(Text[i]);//here when i used Text[i] giv me error: Property or indexer cannot be assigned to -- it is read only
                    
                }
                else if (Text[i - 1] == ' ')
                {
                    Text[i] = ToUpper(Text[i]);// ToUpper Does not exist in current context
                }
            }
            return Text;
        }
        static void Main(string[] args)
        {
            Console.Write(Captilaize("cpp string exercises"));
        }                           
    }
}

【问题讨论】:

    标签: c#


    【解决方案1】:

    为了解决眼前的问题,字符串的索引器是只读

    String.Chars[Int32] Property

    获取当前String中指定位置的Char对象 对象。

    原因,是因为字符串是不可变的(出于一大堆原因),更不用说它们可以被实习了。无论如何,能够改变这样的字符串需要新的分配。

    你要么必须重建字符串,要么使用 char 数组来实现你想要的。

    您的第二个问题是,您需要通过拆分字符串或使用正则表达式来识别单词的构成,然后将大写应用于每个单词的第一个字符。

    但是,您所描述的内容称为标题案例。自.Net 1.1 以来,C# 中就有一种方法可以在 Globalization 命名空间中执行此操作。

    TextInfo.ToTitleCase(String) Method

    将指定的字符串转换为标题大小写(除了 完全大写,被认为是首字母缩略词)。

    示例

    string myString = "Some random string to prove this example";
    var myTI = CultureInfo.CurrentCulture.TextInfo
    
    // or 
    // var myTI = new CultureInfo("en-US",false).TextInfo;
    
    Console.WriteLine( myTI.ToTitleCase( myString ) );
    

    输出

    Some Random String To Prove This Example
    

    Full Demo Here

    【讨论】:

      【解决方案2】:

      ToUpper 是您在字符串上调用的方法,该方法返回所有字母大写的字符串。 您想索引字符串中的第一个字符并仅在此上调用方法。

      【讨论】:

      • 好吧,你真的很想调用Char.ToUpper(),因为字符串中的每个字符都是char
      • 取决于你如何实现它,你可以使用任何一种方法。但基于 OP 的实现,你是对的。
      • 这不是 OP 所要求的,无论如何 - 我想编写一个程序来大写给定字符串的每个单词的第一个字母 我>
      • 好点,在仔细阅读 OP 的帖子后,我同意。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-22
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      相关资源
      最近更新 更多