开发者

C# character counting in a string and add in a period in a string

开发者 https://www.devze.com 2023-01-31 04:07 出处:网络
This one开发者_StackOverflow is really simple but I\'m just not sure how to do it without foreach looping over each line.

This one开发者_StackOverflow is really simple but I'm just not sure how to do it without foreach looping over each line.

What I want to do is place a period (.) after the 6th character in each string.

Input:

ads234adf4234asd  
dfasd234asdf45  
rte3443  
fdf323ggt  
vgdfg767575  
sdgsdfgdfg756756    

Output:

ads234.adf4234asd  
dfasd2.34asdf45  
rte344.3  
fdf323.ggt  
vgdfg7.67575  
sdgsdf.gdfg756756

How can I do this?


For each string you can use string.Insert to get the result you want:

string s = "ads234adf4234asd";
s = s.Insert(6, ".");

If you want to avoid writing an explicit for loop you could try LINQ:

string[] result = lines
    .Select(s => s.Insert(6, "."))
    .ToArray();

Note that this avoids the foreach but it doesn't avoid looping - there's still a loop inside the implementation of Select.

If you don't want the program to crash if it receives a string of length 5 or less but just to return the string unchanged, then try this:

string[] result = lines
    .Select(s => s.Length >= 6 ? s.Insert(6, ".") : s)
    .ToArray();


The following RegEx will insert a . after the 6th character of each line:

Regex.Replace(yourInputString, "^(?<before>.{6})(?<after>.*)$", @"${before}.${after}", RegexOptions.Multiline);


You can use the modulus operator to achieve this. e.g.

string myString = "abcdefghijklmnopqrstuvwxyz";
string newString = "";
for (int i = 0; i < myString.Length; i++)
{
    if (i !=0 && i % 6 == 0)
    {
        newString += ".";
    }
    newString += myString[i];
}


I can't see a way of not looping at all -- if you have it stored as a single char array you could step through each char and insert a period 6 chars after each return/newline char you find.

edit: may have misunderstand foreach looping each line ... do you mean foreach looping from line to line, or looping through the chars in each line?


Well, if you divide the length of the string by 6 you know how many periods to add. So...

// -1 to account for i = 6 in the loop to start
int numPeriods = ( str.Length / 6 ) - 1;

// we increment the index by 7 to account for the period we added
for( int index = 6, i = 0; i < numPeriods; index += 7, ++i )
{
    str = str.Insert( index, "." );
}

I'm sure there is a more elegant way, but I have to get back to work!

Also, your written request and your example are not the same thing. You say

What I want to do is after every 6th character in a string place a '.'

But your example shows adding a period at index 6 for each line. Which is it?


I think that looping is the best way, maybe you could make your code cleaner with LINQ:

var linq = from text in strings
           where text.Length > 6
           select text.Insert(6, ".");


Untested, but t This might works:

string field = "ads234adf4234asd";

int i = 0;
while ((i += 6) < field.Length)
    field = field.Insert(i, ".");

Tested with corrections.

Or, if only after the 6th:

string field = "ads234adf4234asd";

if (field.Length >= 6)
    field = field.Insert(6, ".");


I'm going to reuse some code that I've presented previously that breaks an IEnumerable<T> into pages:

static class EnumerableExtensions {
    public static IEnumerable<IEnumerable<T>> GetPages<T>(
    this IEnumerable<T> source,
    int pageSize
) {
        var e = source.GetEnumerator();
        while (e.MoveNext()) {
            int count = pageSize - 1;
            List<T> list = new List<T>(pageSize) { e.Current };
            while (count > 0 && e.MoveNext()) {
                list.Add(e.Current);
                count--;
            }
            yield return list;
        }
    }
}

Then:

string s = "ads234adf4234asd";
var pages = s.GetPages(6);
string result = String.Join(".", pages.Select(a => new string(a.ToArray())));

Of course, there are loops buried in there which I can't really understand you wanting to avoid. However, if you really must avoid loops, you can do this recursively:

static string SplitAndInsert(string s, int afterEvery, char insertCharacter) {
        if (s.Length < afterEvery) {
            return s;
        }
        else {
            return 
                s.Substring(0, afterEvery) +
                insertCharacter +
                SplitAndInsert(
                    s.Substring(afterEvery, s.Length - afterEvery),
                    afterEvery,
                    insertCharacter
                );
        }
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消