需要实现对一个字符串的处理,首先将该字符串首尾的空格去掉,仅保留一个空格,即允许字符串中间有多个空格,但连续的空格数不可超过一个

答:string inputStr=” xx xx “; inputStr = Regex.Replace(inputStr.Trim(), @”s+”, ” “);

String类中的一些其他常用的方法:

比较字符串
using System;
namespace StringApplication {

class StringProg {

static void Main(string[] args) {
string str1 = “这是一个测试”;
string str2 = “这是一个测试”;

if (String.Compare(str1, str2) == 0) {
Console.WriteLine(str1 + ” 和” + str2 + ” 相等.”);
} else {
Console.WriteLine(str1 + ” 和” + str2 + ” 不相等.”);
}
Console.ReadKey() ;
}
}
}

String包含String
using System;

namespace StringApplication {

class StringProg {

static void Main(string[] args) {
string str = “这是一个测试”;

if (str.Contains(“测试”)) {
Console.WriteLine(“在字符串中找到测试一词.”);
}
Console.ReadKey() ;
}
}
}

获得子串
using System;

namespace StringApplication {

class StringProg {

static void Main(string[] args) {
string str = “昨晚我梦见你”;
Console.WriteLine(str);
string substr = str.Substring(4);
Console.WriteLine(substr);
}
}
}

加入字符串
using System;

namespace StringApplication {

class StringProg {

static void Main(string[] args) {
string[] starray = new string[]{“夜晚是黑暗的”,
“每天阳光照在山顶上”,
“我乘坐一艘帆船旅行”,
“当我到杭州时”,
“我停了下来”};

string str = String.Join(“\n”, starray);
Console.WriteLine(str);
}
}
}

参考:字符串(C#编程指南)

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理