C # 문자열에서 문자 제거
문자열에서 문자를 어떻게 제거합니까? 예를 들면 다음과 같습니다 "My name @is ,Wan.;'; Wan"
..
'@', ',', '.', ';', '\''
해당 문자열 에서 문자가 제거되도록하고 싶습니다."My name is Wan Wan"
var str = "My name @is ,Wan.;'; Wan";
var charsToRemove = new string[] { "@", ",", ".", ";", "'" };
foreach (var c in charsToRemove)
{
str = str.Replace(c, string.Empty);
}
그러나 문자가 아닌 문자를 모두 제거하려면 다른 방법을 제안 할 수 있습니다
var str = "My name @is ,Wan.;'; Wan";
str = new string((from c in str
where char.IsWhiteSpace(c) || char.IsLetterOrDigit(c)
select c
).ToArray());
단순한:
String.Join("", "My name @is ,Wan.;'; Wan".Split('@', ',' ,'.' ,';', '\''));
빠른 텍스트 조작을 위해 설계된 엔진 인 RegEx에 이상적인 응용 프로그램 인 것 같습니다. 이 경우 :
Regex.Replace("He\"ll,o Wo'r.ld", "[@,\\.\";'\\\\]", string.Empty)
질문에 덜 구체적으로, 정규식에 허용되는 문자를 흰색으로 나열하여 문자열에서 공백을 제외한 모든 문장 부호를 제거 할 수 있습니다.
string dirty = "My name @is ,Wan.;'; Wan";
// only space, capital A-Z, lowercase a-z, and digits 0-9 are allowed in the string
string clean = Regex.Replace(dirty, "[^A-Za-z0-9 ]", "");
문장에서 공백을 제거하지 않도록 9 이후에 공백이 있습니다. 세 번째 인수는 정규식에 속하지 않는 하위 문자열을 대체하는 빈 문자열입니다.
string x = "My name @is ,Wan.;'; Wan";
string modifiedString = x.Replace("@", "").Replace(",", "").Replace(".", "").Replace(";", "").Replace("'", "");
다양한 제안 비교 (단일 문자 대체와 관련하여 다양한 크기 및 대상 위치로 비교).
이 경우 대상을 분할하고 교체 (이 경우 빈 문자열)에 참여하는 것이 최소 3 배 이상 빠릅니다. 궁극적으로 교체 횟수에 따라 성능이 달라집니다. 소스 및 소스의 크기 #ymmv
결과
(전체 결과는 여기 )
| Test | Compare | Elapsed |
|---------------------------|---------|--------------------------------------------------------------------|
| SplitJoin | 1.00x | 29023 ticks elapsed (2.9023 ms) [in 10K reps, 0.00029023 ms per] |
| Replace | 2.77x | 80295 ticks elapsed (8.0295 ms) [in 10K reps, 0.00080295 ms per] |
| RegexCompiled | 5.27x | 152869 ticks elapsed (15.2869 ms) [in 10K reps, 0.00152869 ms per] |
| LinqSplit | 5.43x | 157580 ticks elapsed (15.758 ms) [in 10K reps, 0.0015758 ms per] |
| Regex, Uncompiled | 5.85x | 169667 ticks elapsed (16.9667 ms) [in 10K reps, 0.00169667 ms per] |
| Regex | 6.81x | 197551 ticks elapsed (19.7551 ms) [in 10K reps, 0.00197551 ms per] |
| RegexCompiled Insensitive | 7.33x | 212789 ticks elapsed (21.2789 ms) [in 10K reps, 0.00212789 ms per] |
| Regex Insentive | 7.52x | 218164 ticks elapsed (21.8164 ms) [in 10K reps, 0.00218164 ms per] |
테스트 하니스 (LinqPad)
(참고 : Perf
및 Vs
있는 타이밍 확장은 내가 쓴 )
void test(string title, string sample, string target, string replacement) {
var targets = target.ToCharArray();
var tox = "[" + target + "]";
var x = new Regex(tox);
var xc = new Regex(tox, RegexOptions.Compiled);
var xci = new Regex(tox, RegexOptions.Compiled | RegexOptions.IgnoreCase);
// no, don't dump the results
var p = new Perf/*<string>*/();
p.Add(string.Join(" ", title, "Replace"), n => targets.Aggregate(sample, (res, curr) => res.Replace(new string(curr, 1), replacement)));
p.Add(string.Join(" ", title, "SplitJoin"), n => String.Join(replacement, sample.Split(targets)));
p.Add(string.Join(" ", title, "LinqSplit"), n => String.Concat(sample.Select(c => targets.Contains(c) ? replacement : new string(c, 1))));
p.Add(string.Join(" ", title, "Regex"), n => Regex.Replace(sample, tox, replacement));
p.Add(string.Join(" ", title, "Regex Insentive"), n => Regex.Replace(sample, tox, replacement, RegexOptions.IgnoreCase));
p.Add(string.Join(" ", title, "Regex, Uncompiled"), n => x.Replace(sample, replacement));
p.Add(string.Join(" ", title, "RegexCompiled"), n => xc.Replace(sample, replacement));
p.Add(string.Join(" ", title, "RegexCompiled Insensitive"), n => xci.Replace(sample, replacement));
var trunc = 40;
var header = sample.Length > trunc ? sample.Substring(0, trunc) + "..." : sample;
p.Vs(header);
}
void Main()
{
// also see https://stackoverflow.com/questions/7411438/remove-characters-from-c-sharp-string
"Control".Perf(n => { var s = "*"; });
var text = "My name @is ,Wan.;'; Wan";
var clean = new[] { '@', ',', '.', ';', '\'' };
test("stackoverflow", text, string.Concat(clean), string.Empty);
var target = "o";
var f = "x";
var replacement = "1";
var fillers = new Dictionary<string, string> {
{ "short", new String(f[0], 10) },
{ "med", new String(f[0], 300) },
{ "long", new String(f[0], 1000) },
{ "huge", new String(f[0], 10000) }
};
var formats = new Dictionary<string, string> {
{ "start", "{0}{1}{1}" },
{ "middle", "{1}{0}{1}" },
{ "end", "{1}{1}{0}" }
};
foreach(var filler in fillers)
foreach(var format in formats) {
var title = string.Join("-", filler.Key, format.Key);
var sample = string.Format(format.Value, target, filler.Value);
test(title, sample, target, replacement);
}
}
가장 간단한 방법은 다음을 사용하는 것입니다 String.Replace
.
String s = string.Replace("StringToReplace", "NewString");
또 다른 간단한 해결책 :
var forbiddenChars = @"@,.;'".ToCharArray();
var dirty = "My name @is ,Wan.;'; Wan";
var clean = new string(dirty.Where(c => !forbiddenChars.Contains(c)).ToArray());
new List<string> { "@", ",", ".", ";", "'" }.ForEach(m => str = str.Replace(m, ""));
문자열은 문자 배열 일 뿐이므로 Linq를 사용하여 교체를 수행하십시오 (위의 Albin과 유사하며 linq contains 문을 사용하여 교체 수행).
var resultString = new string(
(from ch in "My name @is ,Wan.;'; Wan"
where ! @"@,.;\'".Contains(ch)
select ch).ToArray());
첫 번째 문자열은 문자를 바꿀 문자열이고 두 번째 문자열은 문자를 포함하는 간단한 문자열입니다.
나는 이것을 여기서 버릴 수도 있습니다.
문자열에서 문자를 제거하도록 확장하십시오 :
public static string RemoveChars(this string input, params char[] chars)
{
var sb = new StringBuilder();
for (int i = 0; i < input.Length; i++)
{
if (!chars.Contains(input[i]))
sb.Append(input[i]);
}
return sb.ToString();
}
그리고 다음과 같이 사용할 수 있습니다 :
string str = "My name @is ,Wan.;'; Wan";
string cleanedUpString = str.RemoveChars('@', ',', '.', ';', '\'');
아니면 그냥 이렇게 :
string str = "My name @is ,Wan.;'; Wan".RemoveChars('@', ',', '.', ';', '\'');
여기에 좋은 답변이 많이 있습니다. 여기에 정확성을 테스트하는 데 사용할 수있는 몇 가지 단위 테스트와 함께 내 추가 사항이 있습니다. 내 솔루션은 위의 @Rianne과 비슷하지만 ISet을 사용하여 대체 문자에서 O (1) 조회 시간을 제공합니다. @Albin Sunnanbo의 Linq 솔루션과 유사합니다).
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Returns a string with the specified characters removed.
/// </summary>
/// <param name="source">The string to filter.</param>
/// <param name="removeCharacters">The characters to remove.</param>
/// <returns>A new <see cref="System.String"/> with the specified characters removed.</returns>
public static string Remove(this string source, IEnumerable<char> removeCharacters)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
if (removeCharacters == null)
{
throw new ArgumentNullException("removeCharacters");
}
// First see if we were given a collection that supports ISet
ISet<char> replaceChars = removeCharacters as ISet<char>;
if (replaceChars == null)
{
replaceChars = new HashSet<char>(removeCharacters);
}
IEnumerable<char> filtered = source.Where(currentChar => !replaceChars.Contains(currentChar));
return new string(filtered.ToArray());
}
여기서 NUnit (2.6+) 테스트
using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;
[TestFixture]
public class StringExtensionMethodsTests
{
[TestCaseSource(typeof(StringExtensionMethodsTests_Remove_Tests))]
public void Remove(string targetString, IEnumerable<char> removeCharacters, string expected)
{
string actual = StringExtensionMethods.Remove(targetString, removeCharacters);
Assert.That(actual, Is.EqualTo(expected));
}
[TestCaseSource(typeof(StringExtensionMethodsTests_Remove_ParameterValidation_Tests))]
public void Remove_ParameterValidation(string targetString, IEnumerable<char> removeCharacters)
{
Assert.Throws<ArgumentNullException>(() => StringExtensionMethods.Remove(targetString, removeCharacters));
}
}
internal class StringExtensionMethodsTests_Remove_Tests : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return new TestCaseData("My name @is ,Wan.;'; Wan", new char[] { '@', ',', '.', ';', '\'' }, "My name is Wan Wan").SetName("StringUsingCharArray");
yield return new TestCaseData("My name @is ,Wan.;'; Wan", new HashSet<char> { '@', ',', '.', ';', '\'' }, "My name is Wan Wan").SetName("StringUsingISetCollection");
yield return new TestCaseData(string.Empty, new char[1], string.Empty).SetName("EmptyStringNoReplacementCharactersYieldsEmptyString");
yield return new TestCaseData(string.Empty, new char[] { 'A', 'B', 'C' }, string.Empty).SetName("EmptyStringReplacementCharsYieldsEmptyString");
yield return new TestCaseData("No replacement characters", new char[1], "No replacement characters").SetName("StringNoReplacementCharactersYieldsString");
yield return new TestCaseData("No characters will be replaced", new char[] { 'Z' }, "No characters will be replaced").SetName("StringNonExistantReplacementCharactersYieldsString");
yield return new TestCaseData("AaBbCc", new char[] { 'a', 'C' }, "ABbc").SetName("CaseSensitivityReplacements");
yield return new TestCaseData("ABC", new char[] { 'A', 'B', 'C' }, string.Empty).SetName("AllCharactersRemoved");
yield return new TestCaseData("AABBBBBBCC", new char[] { 'A', 'B', 'C' }, string.Empty).SetName("AllCharactersRemovedMultiple");
yield return new TestCaseData("Test That They Didn't Attempt To Use .Except() which returns distinct characters", new char[] { '(', ')' }, "Test That They Didn't Attempt To Use .Except which returns distinct characters").SetName("ValidateTheStringIsNotJustDistinctCharacters");
}
}
internal class StringExtensionMethodsTests_Remove_ParameterValidation_Tests : IEnumerable
{
public IEnumerator GetEnumerator()
{
yield return new TestCaseData(null, null);
yield return new TestCaseData("valid string", null);
yield return new TestCaseData(null, new char[1]);
}
}
가장 짧은 방법은 LINQ와 string.Concat
다음 을 결합하는 것 같습니다 .
var input = @"My name @is ,Wan.;'; Wan";
var chrs = new[] {'@', ',', '.', ';', '\''};
var result = string.Concat(input.Where(c => !chrs.Contains(c)));
// => result = "My name is Wan Wan"
See the C# demo. Note that string.Concat
is a shortcut to string.Join("", ...)
.
Note that using a regex to remove individual known chars is still possible to build dynamically, although it is believed that regex is slower. However, here is a way to build such a dynamic regex (where all you need is a character class):
var pattern = $"[{Regex.Escape(new string(chrs))}]+";
var result = Regex.Replace(input, pattern, string.Empty);
See another C# demo. The regex will look like [@,\.;']+
(matching one or more (+
) consecutive occurrences of @
, ,
, .
, ;
or '
chars) where the dot does not have to be escaped, but Regex.Escape
will be necessary to escape other chars that must be escaped, like \
, ^
, ]
or -
whose position inside the character class you cannot predict.
Old School in place copy/stomp:
private static string RemoveDirtyCharsFromString(string in_string)
{
int index = 0;
int removed = 0;
byte[] in_array = Encoding.UTF8.GetBytes(in_string);
foreach (byte element in in_array)
{
if ((element == ' ') ||
(element == '-') ||
(element == ':'))
{
removed++;
}
else
{
in_array[index] = element;
index++;
}
}
Array.Resize<byte>(ref in_array, (in_array.Length - removed));
return(System.Text.Encoding.UTF8.GetString(in_array, 0, in_array.Length));
}
Not sure about the efficiency w.r.t. other methods (i.e. the overhead of all the function calls and instantiations that happen as a side effect in C# execution).
I make it extension method and with string array, I think string[]
is more useful than char[]
because char can also be string:
public static class Helper
{
public static string RemoverStrs(this string str, string[] removeStrs)
{
foreach (var removeStr in removeStrs)
str = str.Replace(removeStr, "");
return str;
}
}
then you can use it anywhere:
string myname = "My name @is ,Wan.;'; Wan";
string result = myname.RemoveStrs(new[]{ "@", ",", ".", ";", "\\"});
I needed to remove special characters from an XML file. Here's how I did it. char.ToString() is the hero in this code.
string item = "<item type="line" />"
char DC4 = (char)0x14;
string fixed = item.Replace(DC4.ToString(), string.Empty);
new[] { ',', '.', ';', '\'', '@' }
.Aggregate("My name @is ,Wan.;'; Wan", (s, c) => s.Replace(c.ToString(), string.Empty));
Here's a method I wrote that takes a slightly different approach. Rather than specifying the characters to remove, I tell my method which characters I want to keep -- it will remove all other characters.
In the OP's example, he only wants to keep alphabetical characters and spaces. Here's what a call to my method would look like (C# demo):
var str = "My name @is ,Wan.;'; Wan";
// "My name is Wan Wan"
var result = RemoveExcept(str, alphas: true, spaces: true);
Here's my method:
/// <summary>
/// Returns a copy of the original string containing only the set of whitelisted characters.
/// </summary>
/// <param name="value">The string that will be copied and scrubbed.</param>
/// <param name="alphas">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="numerics">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="dashes">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="underlines">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="spaces">If true, all alphabetical characters (a-zA-Z) will be preserved; otherwise, they will be removed.</param>
/// <param name="periods">If true, all decimal characters (".") will be preserved; otherwise, they will be removed.</param>
public static string RemoveExcept(string value, bool alphas = false, bool numerics = false, bool dashes = false, bool underlines = false, bool spaces = false, bool periods = false) {
if (string.IsNullOrWhiteSpace(value)) return value;
if (new[] { alphas, numerics, dashes, underlines, spaces, periods }.All(x => x == false)) return value;
var whitelistChars = new HashSet<char>(string.Concat(
alphas ? "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" : "",
numerics ? "01234567890" : "",
dashes ? "-" : "",
underlines ? "_" : "",
periods ? "." : "",
spaces ? " " : ""
).ToCharArray());
var scrubbedValue = value.Aggregate(new StringBuilder(), (sb, @char) => {
if (whitelistChars.Contains(@char)) sb.Append(@char);
return sb;
}).ToString();
return scrubbedValue;
}
참고URL : https://stackoverflow.com/questions/7411438/remove-characters-from-c-sharp-string
'Programing' 카테고리의 다른 글
Python 자체 디버거 (PDB) 내에서 여러 줄 명령문을 실행하는 방법 (0) | 2020.06.27 |
---|---|
Entity Framework Code First에서 객체를 분리하려면 어떻게해야합니까? (0) | 2020.06.27 |
"코 루틴"과 "스레드"의 차이점은 무엇입니까? (0) | 2020.06.27 |
C #에서 컴퓨터를 종료하는 방법 (0) | 2020.06.27 |
컨텐츠를 추가하기 전에 requestFeature ()를 호출해야합니다. (0) | 2020.06.27 |