[英]Removing multiple characters from a string in c# using MyString.Remove(x,y)
在我的服務器中運行程序(信標檢測代碼)時,我將收到一個可變大小的字符串,名為io385 。
字符串長度可以根據檢測到的信標數量而變化:
...
所以,有了這個,我的想法是刪除任何無用的東西。 盡管字符串的大小可能會有所不同,但我總是想刪除固定位置上的字節(對於第一個信標,前四個和最后兩個;對於下一個信標,前兩個和最后兩個)。
我開始手動刪除 2 個信標字符串上的無用字節。 但是,我想對此進行優化,以便無論字符串是 46 字節還是 xxxx 字節都能自動工作(否則,我必須為每個可能的字符串長度手動編寫字符刪除過程)。
string io385 = "11210000AAAA0000AAAA0000AAAA0000AAAA0A0A0A0ABF210000BBBB0000BBBB0000BBBB0000BBBB0B0B0B0BBF";
string informacao = String.Copy(io385);
informacao = informacao.Remove(0,4).Remove(40,2).Remove(40,2).Remove(80,2);
int x = io385.Length;
int y = informacao.Length;
Console.WriteLine("Original String: {0}", io385);
Console.WriteLine("Copied String: {0}", informacao);
Console.WriteLine("Original String length: {0}", x);
Console.WriteLine("Copied String length: {0}", y);
給定的
public static IEnumerable<string> GetStuff(string input)
{
Console.WriteLine(input.Length);
if (input.Length == 46)
yield return input.Substring(4, 40);
else
for (var i = 0; i < input.Length; i += 44)
yield return input.Substring(i + 2, 40);
}
用法
var input = "xxxx1234567890123456789012345678901234567890xx";
var input2 = "xx1234567890123456789012345678901234567890xxxx1234567890123456789012345678901234567890xxxx1234567890123456789012345678901234567890xxxx1234567890123456789012345678901234567890xx";
Console.WriteLine(string.Join("\r\n", GetStuff(input)));
Console.WriteLine();
Console.WriteLine(string.Join("\r\n", GetStuff(input2)));
輸出
46
1234567890123456789012345678901234567890
176
1234567890123456789012345678901234567890
1234567890123456789012345678901234567890
1234567890123456789012345678901234567890
1234567890123456789012345678901234567890
一種方法是首先刪除前兩個字符,以便所有“信標”在字符串中的長度相同(44 個字符)。 現在我們可以創建一個循環,從0
到length / 44
,我們跳過iteration * 44
字符(即跳過之前的信標),然后再跳過2
個字符(即該信標的前導 2 40
字符),然后取40
字符(我們關心的字符數)。
在一個方法中,這可能看起來像這樣:
public static string RemoveUselessCharacters(string input)
{
// Add argument validation first
if (string.IsNullOrWhiteSpace(input) || input.Length < 46) return input;
// Just remove the first two characters right away
input = input.Substring(2);
// This will hold the result
var result = new StringBuilder();
// Loop once for every beacon
for (int i = 0; i < input.Length / 44; i++)
{
// Skip previous beacons plus two characters, then take 40 characters
result.Append(string.Concat(input.Skip(i * 44 + 2).Take(40)));
}
// Return just the beacon charcters for all the beacons
return result.ToString();
}
如果你想修改代碼以返回一個List<string>
,其中每個字符串都是一個單獨的信標,很容易做到:
public static List<string> GetBeacons(string input)
{
if (string.IsNullOrWhiteSpace(input) || input.Length < 46)
return new List<string> {input};
input = input.Substring(2);
var result = new List<string>();
for (int i = 0; i < input.Length / 44; i++)
{
result.Add(string.Concat(input.Skip(i * 44 + 2).Take(40)));
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.