java - 字符数组如何工作?

标签 java arrays char

我正在准备面试,我一直在查看练习编码问题,我对代码的解决方案有一些疑问。

问题是:编写一个方法来用“%20”替换字符串中的所有空格。您可以假设字符串末尾有足够的空间来容纳额外的字符,并且给定了字符串的实际长度。 示例:

输入:“我的狗”,6

输出:“我的%20狗”

解决方法:

    void replaceSpaces(char[]str, int length){
     int spaceCount = 0, newLength, i;
     for(i = 0; i <length; i++){
       if(str[i] == ' '){
          spaceCount++;
       }
     }
     newLength = length + spaceCount * 2;
     str[newLength]= '/0';
     for(i= length -1; i>=0; i--){
       if(str[i] == ' '){
         str[newLength - 1] = '0';
         str[newLength - 2] = '2';
         str[newLength - 3] = '%';
         newLength = newLength - 3;
       }else{
         str[newLength -1] = str[i];
         newLength = newLength - 1;
        }
       }
      }

关于此代码的第一个问题是我将如何在主类中实现它?我想更好地了解 char 数组的工作原理,看看我是否可以测试这段代码。

其次,这行是什么意思,目的是什么?我试图查找“/0”在 Java 中的含义,但一无所获:

       str[newLength] = '/0';

第三,为什么我们需要在为 %20 添加空间的代码的后半部分中从 newLength 中减去 3?这是下面的行:

       newLength = newLength - 3;

最佳答案

First question with this code are how would I implement this in the main class? I wanted to get a better idea of how exactly the char array works and see if I can test this code.

答案:您有两个选择。 1.使用eclipse等工具。它为您提供了良好的 UI,可以轻松创建一个包含 main() 函数和调试工具的类供您观察。 2.使用System.out.println(str[i]);在控制台输入目标字符;

Secondly, what does this line mean and what is its purpose? I tried to look up what '/0' means in java but could find nothing:

答案:/0 为NULL,是char 数组中字符串结束的标志。它是关于内存和存储方面的结构。例如,有像这样的虚拟内存“safjlasjlkasjallsjalsaf”如果代码将你的一个字符串保存为“APPLE”,它会像这样保存在某些部分。带有起始索引的“safjlasjlAPPLEllsjalsaf”。 (例如 10)。这意味着变量不知道你的字符串是 APPLE 还是 APPLEllsja.. 所以\0 被标记在你的字符串的末尾,就像这样“safjlasjlAPPLE\0lsjalsaf”

\0也是一个字符,位为000000000。

Thirdly why do we need to subtract 3 from the newLength in the second half of the code where we are adding in space for the %20? This is the line below:

答案: 该行是为了指向下一个for循环的下一个索引。由于 i 和 newLength 是指示目标索引的指针(i 是源字符串,newLength 是目标字符串),所以 newLength 应该像 i (newLength = newLength - 1;)一样每循环一次就减 1。因为3个字符(%20)按顺序存储在dest string中,newLength应该减3而不是1)

关于java - 字符数组如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33151954/

相关文章:

java - 简单的线程管理 - Java - Android

java - 摆脱多余的 while 语句

ios - swift 2.0 : Could not cast value of type '__NSArrayM' (0x10a9348d8) to 'NSDictionary' (0x10a934d60)

php - 简单的 Foreach 循环与棘手的情况

c++ - 为什么常量 char 会中断 Loop 和 Switch 语句

java - 如何使用 JobScheduler 为 Android 定期作业指定初始延迟?

java - 用@Immutable 注释一个不可变的Java 类有什么好处?

Javascript 数组与 Php 数组

c++ - 将 unicode 转换为 char

c++ - 打开文件时出现问题并且可能将文件输入/输出到字符串