当前位置: 首页>>代码示例>>C#>>正文


C# String.Replace方法代码示例

本文整理汇总了C#中String.Replace方法的典型用法代码示例。如果您正苦于以下问题:C# String.Replace方法的具体用法?C# String.Replace怎么用?C# String.Replace使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在String的用法示例。


在下文中一共展示了String.Replace方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetPath

        private static String GetPath(String path, Int32 mode)
        {
            // 处理路径分隔符,兼容Windows和Linux
            var sep = Path.DirectorySeparatorChar;
            var sep2 = sep == '/' ? '\\' : '/';
            path = path.Replace(sep2, sep);

            var dir = "";
            switch (mode)
            {
                case 1:
                    dir = BaseDirectory;
                    break;
                case 2:
                    dir = AppDomain.CurrentDomain.BaseDirectory;
                    break;
                case 3:
                    dir = Environment.CurrentDirectory;
                    break;
                default:
                    break;
            }
            if (dir.IsNullOrEmpty()) return Path.GetFullPath(path);

            // 考虑兼容Linux
            if (!NewLife.Runtime.Mono)
            {
                //if (!Path.IsPathRooted(path))
                //!!! 注意:不能直接依赖于Path.IsPathRooted判断,/和\开头的路径虽然是绝对路径,但是它们不是驱动器级别的绝对路径
                if (path[0] == sep || path[0] == sep2 || !Path.IsPathRooted(path))
                {
                    path = path.TrimStart('~');

                    path = path.TrimStart(sep);
                    path = Path.Combine(dir, path);
                }
            }
            else
            {
                if (!path.StartsWith(dir))
                {
                    // path目录存在,不用再次拼接
                    if (!Directory.Exists(path))
                    {
                        path = path.TrimStart(sep);
                        path = Path.Combine(dir, path);
                    }
                }
            }

            return Path.GetFullPath(path);
        }
开发者ID:tommybiteme,项目名称:X,代码行数:52,代码来源:PathHelper.cs

示例2: Reduce

        internal static String Reduce(String path)
        {
            // ignore query string
            String queryString = null;
            if (path != null)
            {
                int iqs = path.IndexOf('?');
                if (iqs >= 0)
                {
                    queryString = path.Substring(iqs);
                    path = path.Substring(0, iqs);
                }
            }

            int length = path.Length;
            int examine;

            // Make sure we don't have any back slashes
            path = path.Replace('\\', '/');

            // quickly rule out situations in which there are no . or ..

            for (examine = 0; ; examine++)
            {
                examine = path.IndexOf('.', examine);
                if (examine < 0)
                {
                    return (queryString != null) ? (path + queryString) : path;
                }

                if ((examine == 0 || path[examine - 1] == '/')
                    && (examine + 1 == length || path[examine + 1] == '/' ||
                        (path[examine + 1] == '.' && (examine + 2 == length || path[examine + 2] == '/'))))
                {
                    break;
                }
            }

            // OK, we found a . or .. so process it:

            ArrayList list = new ArrayList();
            StringBuilder sb = new StringBuilder();
            int start;
            examine = 0;

            for (;;)
            {
                start = examine;
                examine = path.IndexOf('/', start + 1);

                if (examine < 0)
                {
                    examine = length;
                }

                if (examine - start <= 3 &&
                    (examine < 1 || path[examine - 1] == '.') &&
                    (start + 1 >= length || path[start + 1] == '.'))
                {
                    if (examine - start == 3)
                    {
                        if (list.Count == 0)
                        {
                            throw new Exception(SR.GetString(SR.UrlPath_CannotExitUpTopDirectory));
                        }

                        sb.Length = (int)list[list.Count - 1];
                        list.RemoveRange(list.Count - 1, 1);
                    }
                }
                else
                {
                    list.Add(sb.Length);

                    sb.Append(path, start, examine - start);
                }

                if (examine == length)
                {
                    break;
                }
            }

            return sb.ToString() + queryString;
        }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:85,代码来源:UrlPath.cs

示例3: URTComplexType

            internal URTComplexType(String name, String urlNS, String ns, String encodedNS,
                                    SchemaBlockType blockDefault, bool bSUDSType, bool bAnonymous, WsdlParser parser, URTNamespace xns)
            : base(name, urlNS, ns, encodedNS)
            {
                Util.Log("URTComplexType.URTComplexType name "+this.GetHashCode()+" "+name+" urlNS "+urlNS+" ns "+ns+" encodedNS "+encodedNS+" bSUDStype "+bSUDSType+" bAnonymous "+bAnonymous);
                _baseTypeName = null;
                _baseTypeXmlNS = null;
                _baseType = null;
                _connectURLs = null;
                _bStruct = !bSUDSType;
                _blockType = blockDefault;
                _bSUDSType = bSUDSType;
                _bAnonymous = bAnonymous;
                Debug.Assert(bAnonymous == false || _bSUDSType == false);
                _fieldString = null;
                _fields = new ArrayList();
                _methods = new ArrayList();
                _implIFaces = new ArrayList();
                _implIFaceNames = new ArrayList();
                _sudsType = SUDSType.None;              
                _parser = parser;

                int index = name.IndexOf('+');
                if (index > 0)
                {
                    // Nested type see if outer type has been added to namespace
                    String outerType = parser.Atomize(name.Substring(0,index));
                    URTComplexType cs = xns.LookupComplexType(outerType);
                    if (cs == null)
                    {
                        URTComplexType newCs = new URTComplexType(outerType, urlNS, ns, encodedNS, blockDefault, bSUDSType, bAnonymous, parser, xns);
                        Util.Log("URTComplexType.URTComplexType add outerType to namespace "+outerType+" nestedname "+name);
                        xns.AddComplexType(newCs);
                    }
                }


                if (xns.UrtType == UrtType.Interop)
                {
                    // Interop class names can have '.', replace these with '_', and set wire name to original type name.
                    index = name.LastIndexOf('.');
                    if (index > -1)
                    {
                        // class names can't have '.' so replace with '$'. Use xmlType attribute to send original name on wire.
                        _wireType = name;
                        Name = name.Replace(".", "_");
                        SearchName = name;
                    }
                }

            }
开发者ID:JianwenSun,项目名称:cc,代码行数:51,代码来源:WsdlParser.cs

示例4: writeLetter

 private static String writeLetter(int checkId, String letter)
 {
     Check check = CheckDAO.find(checkId);
     DateTime sendDate = DateTime.Today;
     String checkAddress = check.Account.AccountAddress;
     String accountName = check.Account.AccountFirstName + " " + check.Account.AccountLastName;
     DateTime checkDate = check.CheckDate;
     String storeName = check.Store.StoreName;
     double checkAmnt = check.CheckAmount;
     String bankName = check.Bank.BankName;
     double fee = Convert.ToDouble(check.Store.StoreServiceCharge);
     double totalAmnt = checkAmnt + fee;
     String storeManager = "HardCoded ---"; // TODO: Get an actual store manager value
     String storeAddress = check.Store.StoreAddress;
     return letter
         .Replace("{sendDate}", sendDate.ToShortDateString())
         .Replace("{accountName}", accountName)
         .Replace("{checkDate}", checkDate.ToShortDateString())
         .Replace("{checkAddress}", checkAddress)
         .Replace("{storeName}", storeName)
         .Replace("{checkAmnt}", checkAmnt.ToString("C"))
         .Replace("{bankName}", bankName)
         .Replace("{fee}", fee.ToString("C"))
         .Replace("{totalAmnt}", totalAmnt.ToString("C"))
         .Replace("{storeManager}", storeManager)
         .Replace("{storeAddress}", storeAddress);
 }
开发者ID:captaintino,项目名称:Bounced-Check-Manager,代码行数:27,代码来源:LetterDAO.cs

示例5: AddPrefixToTableName

 private static String AddPrefixToTableName(String tableName)
 {
     if (strUtil.HasText(DbConfig.Instance.TablePrefix))
     {
         tableName = tableName.Replace("[", "").Replace("]", "");
         tableName = DbConfig.Instance.TablePrefix + tableName;
     }
     return tableName;
 }
开发者ID:mfz888,项目名称:xcore,代码行数:9,代码来源:EntityInfo.cs

示例6: MakePolicy

	// Make a policy from host and scheme information.
	private static PolicyStatement MakePolicy(String scheme, String host)
			{
			#if CONFIG_REFLECTION
				// Create the uri corresponding to the parameters.
				if(host != null)
				{
					host = host.Replace(".", "\\.");
				}
				else
				{
					host = ".*";
				}
				String uri;
				if(scheme != null && String.Compare(scheme, "http", true) == 0)
				{
					uri = "(http|https)://" + host + "/.*";
				}
				else if(scheme != null)
				{
					uri = scheme + "://" + host + "/.*";
				}
				else
				{
					uri = ".*://" + host + "/.*";
				}

				// We need to create an instance of "System.Net.WebPermission",
				// but that class does not exist in this assembly.  So, we
				// have to create it in a somewhat round-about fashion.
				Assembly system = Assembly.Load("System");
				Type webPermType = system.GetType
					("System.Net.WebPermission", true, false);
				Object webPerm = Activator.CreateInstance(webPermType);
				Type networkAccessType = system.GetType
					("System.Net.NetworkAccess", true, false);
				Object networkAccess = Enum.ToObject
					(networkAccessType, 0x0040 /* Connect */);
				Type regexType = system.GetType
					("System.Text.RegularExpressions.Regex", true, false);
				Object regex = Activator.CreateInstance
					(regexType, new Object[] {uri});
				webPermType.InvokeMember("AddPermission",
										 BindingFlags.InvokeMethod |
										 BindingFlags.Public |
										 BindingFlags.Instance, null,
										 webPerm,
										 new Object[] {networkAccess, regex});

				// Create a permission set holding the web permission.
				PermissionSet permSet = new PermissionSet
					(PermissionState.None);
				permSet.AddPermission(webPerm as IPermission);

				// Return the final policy statement, from the permission set.
				return new PolicyStatement(permSet);
			#else
				return null;
			#endif
			}
开发者ID:jjenki11,项目名称:blaze-chem-rendering,代码行数:60,代码来源:NetCodeGroup.cs

示例7: LocalSiteString

        public LocalSiteString( String site )
        {
            m_site = site.Replace( '|', ':');

            if (m_site.Length > 2 && m_site.IndexOf( ':' ) != -1)
                throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
                
            m_separatedSite = CreateSeparatedString( m_site );
        }
开发者ID:ArildF,项目名称:masters,代码行数:9,代码来源:urlstring.cs

示例8: WritePlainText

        /// <devdoc>
        ///    <para>[To be supplied.]</para>
        /// </devdoc>
        private void WritePlainText(String text) {
            if (text == null) {
                return;
            }
            if (text.IndexOf('$') != -1) {
                text = text.Replace("$", "$$");
            }

            Write(text);
        }
开发者ID:iskiselev,项目名称:JSIL.NetFramework,代码行数:13,代码来源:WmlTextWriter.cs

示例9: EvaluatePropertyName

 PropertyNameType EvaluatePropertyName(String pName)
 {
     PropertyNameType lType = PropertyNameType.Unknown;
     if (!Enum.TryParse(pName.Replace(" ", "_"), true, out lType))
     {
         // Not a basic Type..
         WeaponTypes temp;
         if (Enum.TryParse(pName.Replace(" ", "_"), true, out temp))
         {
             // weapon..
             lType = PropertyNameType.Weapon;
         }
         else
         {
             // maybe it's a spell
             if (pName.Contains(','))
             {
                 lType = PropertyNameType.SkillGem;
                 String[] tokens = pName.Split(',');
                 foreach (String s in tokens)
                 {
                     SkillTypes type = SkillTypes.Unknown;
                     if (Enum.TryParse(s, out type))
                     {
                         SkillGemTypes.Add(type);
                     }
                 }
             }
             else
             {
                 // It may still be a spell..
                 SkillTypes type = SkillTypes.Unknown;
                 if (Enum.TryParse(pName, out type))
                 {
                     lType = PropertyNameType.SkillGem;
                     SkillGemTypes.Add(type);
                 }
                 else
                 {
                     lType = PropertyNameType.Unknown;
                 }
             }
         }
     }
     return lType;
 }
开发者ID:jarneson,项目名称:exiled-toolkit,代码行数:46,代码来源:ToolkitObjects.cs

示例10: AddValues

 // Helper function to add multiple values for the same key
 private void AddValues(NameValueCollection sourceCollection,
                        String sourceKey,
                        NameValueCollection targetCollection)
 {
     String [] values = sourceCollection.GetValues(sourceKey);
     foreach (String value in values)
     {
         if(Device.RequiresAttributeColonSubstitution)
         {
             targetCollection.Add(sourceKey.Replace(',',':'), value);
         }
         else
         {
             targetCollection.Add(sourceKey, value);
         }
     }
 }
开发者ID:iskiselev,项目名称:JSIL.NetFramework,代码行数:18,代码来源:ChtmlPageAdapter.cs

示例11: WriteEncodedText

        /// <devdoc>
        /// <para>[To be supplied.]</para>
        /// </devdoc>
        public override void WriteEncodedText(String text) {
            if (text == null) {
                return;
            }
            if (text.IndexOf('$') != -1) {
                text = text.Replace("$", "$$");
            }

            base.WriteEncodedText(text);
        }
开发者ID:iskiselev,项目名称:JSIL.NetFramework,代码行数:13,代码来源:WmlTextWriter.cs

示例12: FilenameToURL

	// Convert a filename into a URL.
	internal String FilenameToURL(String name)
			{
				String temp;
				bool checkOther;

				// Bail out if the name is empty.
				if(name == null || name.Length == 0)
				{
					return null;
				}
				
				// Get the full absolute pathname for the file.
				checkOther = true;
				if(!Path.IsPathRooted(name) && linkDirectory != null)
				{
					temp = Path.Combine(linkDirectory, name);
					if(File.Exists(temp))
					{
						name = temp;
						checkOther = false;
					}
				}
				if(checkOther && !Path.IsPathRooted(name) && filename != null)
				{
					temp = Path.Combine
						(Path.GetDirectoryName(filename), name);
					if(File.Exists(temp))
					{
						name = temp;
					}
				}
				name = Path.GetFullPath(name);

				// Normalize pathname separators to "/".
				name = name.Replace('\\', '/');

				// Add the "file:" prefix to the name to form the URL.
				if(name.Length >= 2 && name[1] == ':')
				{
					// The filename includes a Windows-style drive letter.
					return "file:/" + name;
				}
				else
				{
					// The filename is absolute from a Unix-style root.
					return "file:" + name;
				}
			}
开发者ID:jjenki11,项目名称:blaze-chem-rendering,代码行数:49,代码来源:SymReader.cs

示例13: EncodeTab

    //
    // Implemenation of IManagedContext
    //

    // As we use tab as separator, marshaling data will be corrupted
    // when user inputs contain any tabs. Therefore, we have tabs in user
    // inputs encoded before marshaling (Dev10 #692392)
    private static String EncodeTab(String value) {
        if (String.IsNullOrEmpty(value) || value.IndexOfAny(TabOrBackSpace) < 0) {
            return value;
        }
        return value.Replace("\b", "\bB").Replace("\t", "\bT");
    }
开发者ID:krytht,项目名称:DotNetReferenceSource,代码行数:13,代码来源:AspCompat.cs

示例14: TranslateAndAppendText

        static internal void TranslateAndAppendText(String text, StringWriter writer)
        {
            // Can't quite use HtmlDecode, because HtmlDecode doesn't
            // parse &nbsp; the way we'd like it to.

            if (text.IndexOf('&') != -1)
            {
                if (text.IndexOf("&nbsp;", StringComparison.Ordinal) != -1)
                {
                    text = text.Replace("&nbsp;", "\u00A0");
                }

                HttpUtility.HtmlDecode(text, writer);
            }
            else
            {
                writer.Write(text);
            }
        }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:19,代码来源:MobileControl.cs

示例15: QuoteSnippetString

	// Quote a snippet string.
	protected override String QuoteSnippetString(String value)
			{
				return "\"" + value.Replace("\"", "\"\"") + "\"";
			}
开发者ID:jjenki11,项目名称:blaze-chem-rendering,代码行数:5,代码来源:VBCodeCompiler.cs


注:本文中的String.Replace方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。