0
Follow
0
View

c#, about inserting commas between strings

dragenlong 注册会员
2023-02-28 02:55

img

img

The final code is the code in Figure 2

string resultString =@ “31323531a102SgP“;
try {
    resultString = Regex.Replace(subjectString, ".{2}", "$0,");
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}

djnandy 注册会员
2023-02-28 02:55
< div class = "md_content_show e397 data - v - 3967" = "" >

regular yyds

dzfu123 注册会员
2023-02-28 02:55

the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > you can use string functions and insert a comma in the cycle to the given string. Here is an example code written in Python that inserts a comma between every two characters:

string = "31323531a102SgP"
new_string = ""

for i in range(0, len(string), 2):
    new_string += string[i:i+2] + ","

# 移除最后一个逗号
new_string = new_string[:-1]

print(new_string)

This code divides the string into groups of two characters and inserts a comma between each group. The last comma needs to be removed after the loop ends. The output is:

31,32,35,31,a1,02,Sg,P

You can modify this code as needed, such as changing the group size or changing the separator.

dj721111 注册会员
2023-02-28 02:55

Hope to adopt ha, thank you! 1, the solution is as follows

img

string newStr = string.Empty;
string str = "31323531a102SgP";
for (int i = 0; i < str.Length; i++)
{
    if (i > 0 && i % 2 == 0)
    {
        newStr += ',';
    }
    newStr += str[i].ToString();
}
newStr = newStr.TrimEnd(','); // 把最后一个逗号移除
ddk35785 注册会员
2023-02-28 02:55

This answer references ChatGPT
You can Insert commas between every two characters using the string insert method. The specific methods are as follows:

string str = "31323531a102SgP";
string result = string.Empty;

for (int i = 0; i < str.Length; i += 2)
{
    result += str.Substring(i, 2) + ",";
}

// 去掉最后一个逗号
result = result.Remove(result.Length - 1);

Console.WriteLine(result);


A loop is used here, taking two characters at a time from the original string and concatenating them with a comma into a new string. Finally, we need to remove the last comma to get the final result. In this example, the final output is: 31,32,35,31,a1,02,Sg,P.

dytcc23 注册会员
2023-02-28 02:55

toCharArray to char array, loop concatenation

About the Author

Question Info

Publish Time
2023-02-28 02:55
Update Time
2023-02-28 02:55