开发者

String division

I want to print th开发者_运维技巧e string " my name is xxx" as "xxx is name my" with out using Special methods (like util package methods in java); thanks


  String text = "my name is xxx";
  String reversed = "";
  for (String word : text.split(" ")) {
     reversed = word + " " + reversed;
  }
  reversed = reversed.trim();

If absolutely no method call is allowed, then it's a bit messier.

  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);

This requires a bit more explanation. We read the input array right to left (i--), and whenever we find a space, or when we eventually hit the left wall (i == -1), we copy (for k) the word we found to the output array ([j++] =). We keep track of the word boundaries in last.


FYI, the String class lives in the java.lang package.


I don't know Java, but here is the worst case approach.

If you don't want to use split() method, then

  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());

If this is homework and its transferred to some one, then you are the looser

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜