简体   繁体   English

如何用立即字符替换字符串的下一个字符

[英]How to replace next Character of string with immediate character

I am trying to replace next character of string with immediate character. 我试图用立即数替换字符串的下一个字符。 For example, given string is "HOME" 例如,给定的字符串为"HOME"

required string should be "EHOM" , 必需的字符串应为"EHOM"

Is it possible to do it without any replace function. 有没有任何替换功能就可以做到吗?

Seems like just moving the last character in front: 好像只是将最后一个字符移到前面:

string s = "HOME";
s = s.Last() + s.Remove(s.Length - 1);   // "EHOM"

approach "doing everything on foot": 处理“徒步做所有事情”:

make a char array as long as your string ... (no trailing null) 只要您的字符串,就创建一个char数组...(无尾随null)

have a for loop with the index i go through the array 有索引的我循环通过数组

calculate the replacement position r = i - 1 + len(array) mod len(array) 计算替换位置r = i-1 + len(array)mod len(array)

fetch char from position r in the original string 从原始字符串中的位置r获取char

put fetched char at position i of your array 将获取的字符放在数组的位置i

end of loop 循环结束

make a string from your array 从数组中创建一个字符串

Basic string functions: 基本的字符串函数:

    string x = "Home";
    string y = x.Substring(x.Length - 1, 1) + x.Substring(0, x.Length - 1);

Please note that you should declare a new string to respect immutability. 请注意,您应该声明一个新字符串以尊重不变性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM