我想打印字符串“my name is xxx”作为“xxx is name my”,而不使用Special方法(比如java中的util包方法); 感谢
答案 0 :(得分:5)
String text = "my name is xxx";
String reversed = "";
for (String word : text.split(" ")) {
reversed = word + " " + reversed;
}
reversed = reversed.trim();
如果绝对不允许方法调用,那就有点麻烦了。
String text = "my name is xxx";
char[] letters = text.toCharArray();
char[] srettel = new char[letters.length];
for (int last = letters.length, i = last - 1, j = 0; i >= -1; i--) {
if (i == -1 || letters[i] == ' ') {
for (int k = i + 1; k < last; ) {
srettel[j++] = letters[k++];
}
if (i != -1) srettel[j++] = ' ';
last = i;
}
}
String reversed = new String(srettel);
这需要更多解释。我们从右到左阅读输入数组(i--
),每当我们找到一个空格,或者当我们最终到达左墙(i == -1
)时,我们复制(for k
)这个词我们找到了输出数组([j++] =
)。我们会在last
中跟踪单词边界。
答案 1 :(得分:1)
仅供参考,String类位于 java.lang 包中。
答案 2 :(得分:0)
我不懂Java,但这是最坏的情况。
如果您不想使用split()方法,那么
string text = "My name is Khan";
int length = text.Length;
int numberOfWords = 0;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == ' ')
{
numberOfWords++;
}
}
numberOfWords += 1; // no of words will be always plus one than no of space.
string[] wordCollection = new string[numberOfWords];
int wordLocation = 0;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == ' ')
{
wordLocation++;
}
wordCollection[wordLocation] += text[i];
}
string reversedString = string.Empty;
foreach (string str in wordCollection)
{
reversedString = str + " " + reversedString;
}
Console.Write(reversedString.Trim());
如果这是作业并将其转移到某个作业,那么你就是更宽松的